Chapter 5
Chapter 5
CHAPTER - 5
Exception Handling
Content of the lecture
Exception
Types Of Exception
Exception Handling
Hierarchy of Exception Handling
Try-Catch-Final Blocks,
User Defined Exceptions
Exception Handling
Predefined exception
There is pre defined class Java.lang.Error that used to deal with those problems.
Checked exception
Unchecked exception
Types of Exception Handling
Example:
java.lang.ArrayIndexOutOfBoundsException: 2
at
ExceptionExample.main(ExceptionExample.java:4)
What exception class? ArrayIndexOutOfBoundsException
Which array index is out of bounds? 2
What method throws the exception? main
exception?
Example without Exception Handling
Example with Exception Handling
Output:
Denominator can’t be Zero
try and catch block
Output
Catching Multiple Exceptions
Handle multiple possible exceptions by multiple successive catch blocks
try {
// code that might throw multiple exception
}
catch (IOException e) {
// handle IOException and all subclasses
}
catch (ClassNotFoundException e2) {
// handle ClassNotFoundException
}
Rule: At a time only one Exception is occurred and at a time only one catch
block is executed.
Example
Output
Compile Time Error
Example : Multi catch block
If you have to perform different
tasks at the occurrence of
different Exceptions, use java
multi catch block.
Output
task1 completed
rest of the code...
Java Nested try block
Syntax:
Java Nested try block: The try
block within a try block is known ....
try
as nested try block in java.
{ statement 1;
Why use nested try block: statement 2;
try
Sometimes a situation may arise
{ statement 1;
where a part of a block may statement 2;
} catch(Exception e) {
cause one error and the entire
} }
block itself may cause another catch(Exception e)
{ }
error. In such cases, exception
....
handlers have to be nested.
Java nested try example
Throws