4 Exception Handling
4 Exception Handling
4 Exception Handling
Exception handling
• The Exception Handling in Java is one of the powerful mechanism to handle the runtime
errors so that the normal flow of the application can be maintained.
• Exceptions are runtime errors in a program, which violate system constraints. For
example, when the program attempts to divide a number by zero, an exception occurs.
When an exception occurs, the system catches it and raises the exception.
• If the program doesn’t handle the exception properly, it will crash. For example, the
following program will crash due to an exception:
int amount = 100;
int qty = 0;
int result = amount / qty;
Console.WriteLine(result);
• System.DivideByZeroException: 'Attempted to divide by zero.
• In this error message, the exception name is System.DivideByZeroException. And the
error message indicates that the program attempted to divide by zero.
1
• Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc…
• What is Exception?
• Exception is an abnormal condition.
• In Java, an exception is an event that disrupts the normal flow of the program. It is an
object which is thrown at runtime.
2
Advantages of Exception Handling
• The core advantage of exception handling is to maintain the normal flow of the application. An
exception normally disrupts the normal flow of the application; that is why we need to handle
exceptions.
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
• Suppose there are 10 statements in a Java program and an exception occurs at statement 5; the
rest of the code will not be executed, i.e., statements 6 to 10 will not be executed. However, when
we perform exception handling, the rest of the statements will be executed. That is why we use
exception handling in Java. 3
Did you know
• What is the difference between checked and unchecked exceptions?
• What happens behind the code int data=50/0;?
• Why use multiple catch block?
• Is there any possibility when the finally block is not executed?
• What is exception propagation?
• What is the difference between the throw and throws keyword?
• What are the 4 rules for using exception handling with method overriding?
4
Hierarchy of Java Exception classes
5
Check and Unchecked Exception
6
Arithmetic Exception
If we divide any number by zero, there occurs an ArithmeticException.
public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){
System.out.println(e);
}
8
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.
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
9
ArrayIndexOutOfBoundsException
• When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs.
10
Java try block
• 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.
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{
} 11
Java catch block
• Java catch block is used to handle the Exception by declaring the type of exception within
the parameter. The declared exception must be the parent class exception ( i.e.,
Exception) or the generated exception type. However, the good approach is to declare the
generated type of exception.
• The catch block must be used after the try block only. You can use multiple catch block
with a single try block.
12
Internal Working of Java try-catch block
• The JVM firstly checks whether the exception is handled or not. If exception is not
handled, JVM provides a default exception handler that performs the following tasks:
• Prints out exception description.
• Prints the stack trace (Hierarchy of methods where the exception occurred).
• Causes the program to terminate.
• But if the application programmer handles the exception, the normal flow of the
application is maintained, i.e., rest of the code is executed.
13
14
Problem without exception handling
public class TryCatchExample1 {
public static void main(String[] args) {
int data=50/0; //may throw exception
System.out.println("rest of the code");
}
}
19
Solve the exception in catch block
public class TryCatchExample6 {
public static void main(String[] args) {
int i=50;
int j=0;
int data;
try
{
data=i/j; //may throw exception
}
// handling the exception
catch(Exception e)
{
// resolving the exception in catch block - just like plan B
System.out.println(i/(j+2));
}
}
20
}
exception code in a catch block
public class TryCatchExample7 {
public static void main(String[] args) {
try
{
int data1=50/0; //may throw exception
}
// handling the exception
catch(Exception e)
{
// generating the exception in catch block
int data2=50/0; //may throw exception
}
System.out.println("rest of the code");
}
}
// Exception in thread "main" java.lang.ArithmeticException: / by zero
21
In this example, we handle the generated exception (Arithmetic Exception) with a different
type of exception class (ArrayIndexOutOfBoundsException).
Point 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.
24
25
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)
{ Arithmetic Exception occurs
System.out.println("Parent Exception occurs"); rest of the code
} // each time one exception occur
And handle only one exception
System.out.println("rest of the code");
}
} 26
public class MultipleCatchBlock2 {
public static void main(String[] args) {
try block contains two exceptions. But at a time only one
try{ exception occurs and its corresponding catch block is executed.
int a[]=new int[5];
System.out.println(a[10]);
}
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");
}
} ArrayIndexOutOfBounds Exception occurs
rest of the code 27
In this example, we generate NullPointerException, but didn't provide the corresponding exception type. In
such case, the catch block containing the parent exception class Exception will invoked.
public class MultipleCatchBlock4 {
public static void main(String[] args) {
try{
String s=null;
System.out.println(s.length());
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e) Parent Exception occurs
{
System.out.println("Parent Exception occurs"); java.lang.NullPointerException
System.out.println(e); rest of the code
}
System.out.println("rest of the code");
}
} 28
Let's see an example, to handle the exception without maintaining the order of exceptions (i.e.
from most specific to most general).
class MultipleCatchBlock5{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(Exception e){System.out.println("common task completed");}
catch(ArithmeticException e){System.out.println("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
System.out.println("rest of the code...");
}
}
// Compile-time error 29
Finally block
• Java finally block is a block used to
execute important code such as
closing the connection, etc.
• Java finally block 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.
30
Why use finally block
• finally block in Java can be used to put "cleanup" code such as closing a file,
closing connection, etc.
• The important statements to be printed can be placed in the finally block.
• Rule: For each try block there can be zero or more catch blocks, but only one
finally block.
31
When an exception does not occur
Let's see the below example where the Java program does not throw any exception, and the finally block is executed
after the try block.
class TestFinallyBlock {
public static void main(String args[]){
try{
//below code do not throw any exception
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){ //catch won't be executed
System.out.println(e);
}
finally { //executed regardless of exception occurred or not
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
5
Finally block is always executed 32
Rest of the code
When an exception occur but not handled by the catch block
Let's see the following example. Here, the code throws an exception however the catch block cannot handle it.
Despite this, the finally block is executed after the try block and then the program terminates abnormally.
public class TestFinallyBlock1{
public static void main(String args[0]){
try {
System.out.println("Inside the try block");
int data=25/0; //below code throws divide by zero exception
System.out.println(data);
}
//cannot handle Arithmetic type exception
//can only accept Null Pointer type exception
catch(NullPointerException e){
System.out.println(e);
}
//executes regardless of exception occured or not
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
33
Java code throws an exception and the catch block handles the exception. Later the finally block is executed after the try-catch
block. Further, the rest of the code is also executed normally.
public class TestFinallyBlock2{
public static void main(String args[]){
try {
System.out.println("Inside try block");
//below code throws divide by zero exception
int data=25/0;
System.out.println(data);
}
//handles the Arithmetic Exception / Divide by zero exception
catch(ArithmeticException e){
System.out.println("Exception handled");
System.out.println(e);
}
//executes regardless of exception occured or not Exception Handled
finally { Java.lang.ArithmeticException
System.out.println("finally block is always executed");
Finally block is always executed
}
rest of the code …
System.out.println("rest of the code...");
}
} 34