Chapter 4 Exceptions Short Lecture
Chapter 4 Exceptions Short Lecture
10
Exception Handling
import java.util.Scanner;
21
Exception handling…
Exception handling…
import java.util.*;
do {
try {
System.out.print("Enter an integer: ");
int number = scanner.nextInt();
If an exception occurs on this line,
the rest of lines in the try block are
skipped and the control is // Display the result
transferred to the catch block. System.out.println(
"The number entered is " + number);
continueInput = false;
}
catch (InputMismatchException ex) {
System.out.println("Try again. (" +
"Incorrect input: an integer is required)");
scanner.nextLine(); // discard input
}
} while (continueInput);
}
23 }
Exception handling…
Exception handling…
Example:
java import java.io.*;
public class ExcepTest{
public static void main(String args[]){
try{
int a[] = new int[2];
System.out.println("Access element three :"+ a[3]);
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block");
}
}
Exception handling…
try { try {
..….. ..…..
} }
catch(Exception ex){ catch(RuntimeException ex){
……. ……
} }
catch (RuntimeException ex) { catch (Exception ex ) {
…….. ……..
} }
Output:
Exception thrown:java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed
Exception handling…
Note the followings:
A catch clause cannot exist without a try statement.
It is not compulsory to have finally clauses when ever
a try/catch block is present.
The try block cannot be present without either catch
clause or finally clause.
Any code cannot be present in between the try, catch,
finally blocks.
Exception handling…
The throws/throw Keywords:
In any method that might throw an exception, you may
declare the method as “throws” that exception, and
thus avoid handling the exception yourself.
The throws keyword appears at the end of a method's
signature.
public void myMethod()throws IOException
Example
public void myMethod throws IOException {
normal code with some I/O
}
Every method must declare the types of checked
exceptions it might throw using throws keyword.
Exception handling…
• A method can declare that it throws more than one
exception, in which case the exceptions are declared
in
a list separated by commas.
35
Exception handling…
Example
Suppose that method p1 invokes method p2 and p2 may
throw a checked exception (e.g., IOException).
36
Exception handling…
Getting Information from Exception
An Exception object contains valuable information
about the exception. You may use the following
instance methods in the java.lang.Throwable class
to get information regarding the exception.