Exception Handling
• The Exception Handling is one of the
powerful mechanism to handle the runtime errors so
that the normal flow of the application can be
maintained.
• Exception is an abnormal condition.
• Example:
ClassNotFoundException, IOException, SQLException,
RemoteException, etc.
Exception Handling
Hierarchy of Java Exception classes
• The java.lang.Throwable class is the root class
of Java Exception hierarchy inherited by two
subclasses: Exception and Error.
Exception Handling
Exception Handling
Types of Exceptions:
• There are mainly two types of exceptions: checked
and unchecked.
• An error is considered as the unchecked exception.
There are three types of exceptions namely:
1. Checked Exception
2. Unchecked Exception
3. Error
Exception Handling
Exception Handling
1) Checked Exception
• The classes that directly inherit the Throwable class
except RuntimeException and Error are known as
checked exceptions.
• For example, IOException, SQLException, etc.
Checked exceptions are checked at compile-time.
Exception Handling
2) Unchecked Exception
• The classes that inherit the RuntimeException are
known as unchecked exceptions.
• For example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc.
• Unchecked exceptions are not checked at compile-time,
but they are checked at runtime.
Exception Handling
3) Error
• Error is irrecoverable.
• Examples:
OutOfMemoryError, VirtualMachineError,
AssertionError etc.
Exception Handling
Keywords:
• Java provides five keywords that are used to handle
the exception.
1. Try
2. Catch
3. Finally
4. Throw
5. Throws
Exception Handling
Try Block:
• The "try" keyword is used to specify a block where
we should place an exception code.
• It means we can't use try block alone.
• The try block must be followed by either catch or
finally.
Exception Handling
Catch Block:
• The "catch" block is used to handle the exception.
• It must be preceded by try block which means we
can't use catch block alone.
• It can be followed by finally block later.
Exception Handling
Finally Block:
• The "finally" block is used to execute the necessary
code of the program.
• It is executed whether an exception is handled or
not.
Throw:
• The "throw" keyword is used to throw an exception.
Exception Handling
Throws:
• The "throws" keyword is used to declare exceptions.
• It specifies that there may occur an exception in the
method.
• It doesn't throw an exception.
• It is always used with method signature.
Exception Handling
public class TryCatchExample1 {
public static void main(String[] args) {
int data=50/0;
System.out.println("rest of the code");
} }
Output:
Exception in thread "main"
java.lang.ArithmeticException: / by zero
“ the rest of the code is not executed “
Exception Handling
public class JavaExceptionExample{
public static void main(String args[]){
try{
int data=100/0; //code that may raise exception
}
catch(ArithmeticException e){
System.out.println(e);}
System.out.println("rest of the code..."); } }
Output:
java.lang.ArithmeticException: / by zero
rest of the code...
Exception Handling
NullPointerException
If we have a null value in any variable, performing any
operation on the variable throws a NullPointerException.
Example:
String s=null;
System.out.println(s.length())
Exception Handling
NumberFormatException
• If the formatting of any variable or number is mismatched, it
may result into NumberFormatException.
• Suppose we have a String variable that has characters;
converting this variable into digit will cause
NumberFormatException.
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException
Exception Handling
ArrayIndexOutOfBoundsException
• When an array exceeds to it's size, the
ArrayIndexOutOfBoundsException occurs.
Consider the following statements.
1. int a[]=new int[5];
2. a[10]=50; //ArrayIndexOutOfBoundsException
Exception Handling
• Java try block is used to enclose the code that might
throw an exception. It must be used within the
method.
• If an exception occurs at the particular statement in
the try block, the rest of the block code will not
execute. So, it is recommended not to keep the code
in try block that will not throw an exception.
• Java try block must be followed by either catch or
finally block.
Exception Handling
Syntax of Java try-catch
try{
//code that may throw an exception
}catch(Exception_class_Name ref){}
Syntax of try-finally block
try{
//code that may throw an exception
}finally{}
Exception Handling
public class TryCatchExample9 {
public static void main(String[] args) {
try {
int arr[]= {1,3,5,7};
System.out.println(arr[10]); }
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e); }
System.out.println("rest of the code"); } }
Output:
java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 4
rest of the code
Exception Handling
Multi-catch block:
• A try block can be followed by one or more catch blocks.
Each catch block must contain a different exception
handler. So, if you have to perform different tasks at the
occurrence of different exceptions, use java multi-catch
block.
Points to remember
• At a time only one exception occurs and at a time only
one catch block is executed.
• All catch blocks must be ordered from most specific to
most general, i.e. catch for ArithmeticException must
come before catch for Exception.
Exception Handling
public class MultipleCatchBlock1 {
public static void main(String[] args) {
try{
int a[]=new int[5];
a[5]=30/0; }
catch(ArithmeticException e) {
System.out.println("Arithmetic Exception occurs"); }
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBounds Exception occurs"); }
catch(Exception e) {
System.out.println("Parent Exception occurs"); }
System.out.println("rest of the code"); } }
Output:
Arithmetic Exception occurs
rest of the code
Exception Handling
• finally block is a block used to execute important
code such as closing the connection, etc.
• It is always executed whether an exception is
handled or not. Therefore, it contains all the
necessary statements that need to be printed
regardless of the exception occurs or not.
• The finally block follows the try-catch block.
Exception Handling
• Finally Block:
Case 1: When an exception does not occur
Finally Block
• This program does not throw any exception, and the finally
block is executed after the try block.
Case 2: When an exception occur but not handled by
the catch block : Finally Block
Case 3: When an exception occurs and is handled
by the catch block : Finally Block
Nested try block
• The Try block used inside another try block is called
as nested try block. Every statement that we enter a
statement in try block, context of that exception is
pushed onto the stack.
Nested try block
throw Exception
• The Java throw keyword is used to throw an
exception explicitly.
• We specify the exception object which is to be
thrown.
• The Exception has some message with it that
provides the error description.
• These exceptions may be related to user inputs,
server, etc.
throw Exception
The syntax of the Java throw keyword is
• throw new exception_class("error message");
Example:
• throw new IOException("sorry device error");
throw Exception
throws keyword
• The Java throws keyword is used to declare an
exception. It gives an information to the programmer
that there may occur an exception.
• Exception Handling is mainly used to handle the
checked exceptions.
• If there occurs any unchecked exception such as
NullPointerException, it is programmers' fault that he
is not checking the code before it being used.
throws keyword
Syntax
return_type method_name() throws exception_class_name
{
//method code
}
throws keyword