2. Definition
An exception represents an error
condition that can occur during the
normal course of program execution.
Examples
Division by zero
Trying to open an input file that does not
exist
An array index that goes out of bounds
3. Java’s Mechanism of Exception
Handling
When an exception occurs, an object of
a particular exception class can be
created and thrown.
The exception-handling routine can then
be executed to catch & handle the
exception object; we say the thrown
exception is caught.
The normal sequence of flow is
terminated if the exception object is
thrown.
4. Exception thrown
Scanner scan = new Scanner(System.in);
int num = 0;
System.out.print(“Enter an integer>”);
num = scan.nextInt();
System.out.println(“The number you entered is “ +num);
Enter an integer> three
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at ExceptionTest.main(ExceptionTest.java:11)
Error message for invalid input
5. Java’s Mechanism of Exception
Handling (continued)
Java provides a number of exception
classes to effectively handle certain
common exceptions such as division by
zero, invalid input, and file not found
Example:
When a Scanner object is used to input
data into a program, any invalid input
errors are handled using the class
InputMismatchException
When a division by zero exception occurs,
the program creates an object of the
class ArithmeticException
6. Exception Types
All types of thrown exception objects are
instances of the Throwable class or its
subclasses.
Serious errors are represented by
instances of the Error class or its
subclasses.
Exceptional cases that common
applications should handle are
represented by instances of the
Exception class or its subclasses.
8. Catching an Exception
Use try{} and catch{} block
To catch an exception:
Put code that might throw an exception inside a try{} block.
Put code that handles the exception inside a catch{} block.
try {
// statements, some of which might
// throw an exception
}
catch ( SomeExceptionType ex ) {
// statements to handle this
// type of exception
}
9. Catching an Exception
Scanner scan = new Scanner(System.in);
int num = 0;
try {
System.out.print(“Enter an integer>”);
num = scan.nextInt();
} catch (InputMismatchException e){
System.out.println(“Invalid input! Please enter
digits only");
}
System.out.println(“The number you entered is “ +num);
try
catch
11. Getting Information
There are two methods we can call to
get information about the thrown
exception:
getMessage
printStackTrace
try {
. . .
} catch (NumberFormatException e){
System.out.println(e.getMessage());
System.out.println(e.printStackTrace());
}