Handle Exceptions using Try-Catch Block
Now, we know what exceptions are in Java. It’s time to learn how we can handle them. Try-catch block is one such mechanism using which we can handle exceptions.
Try block
Try block is used to enclose the piece of code that is prone to throw one or more exceptions. If we know a piece of code may throw one or more exceptions, we can put it inside a try block in order to handle it.
The best way to use try block is to enclose only those lines which can throw exceptions. If there is just one such line, we should enclose only that line inside the try block.
Note -> Please note that the scope of variables defined inside a try block is limited to that try block only.
Note -> Please note that try block cannot exist alone. It should have either catch or finally block associated with it.
syntax of try block :
try {
//code likely to throw an exception
//code likely to throw an exception
//code likely to throw an exception
}
Catch block
Catch block in used in conjunction with the try block. It means, catch block alone cannot exist. Catch block is used to catch the exception that is thrown from its associated try block.
Catch block doesn’t execute always. It only executes when an exception occurs. Let’s see its syntax
Syntax :
try {
//code likely to throw an exception
} catch (Exception e) {
//code to handle the exception
e.printStackTrace(); //this line will print the details of the exception on the console
}
How to catch multiple exceptions
If try block may throw more than one exception type, then we have to handle all of them using multiple catch blocks.
try {
//code likely to throw an exception
} catch (IOException e) {
//code to handle the exception
e.printStackTrace(); //this line will print the details of the exception on the console
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Note -> While using multiple catch blocks, we have to make sure that the Higher Exception type must be handled after the lower Exception type. Example, Exception which is the highest in the exception class hierarchy, must be the last exception in the catch blocks, as shown in the above code also.
Note -> Unrelated Exception types can be in any order. Such as AirthmeticException and FileNotFoundException.
Example 1
What happens if we don’t handle exceptions?
The below code will throw NullpointerException when the program is run. First, lets see what happens if we don’t handle it using try-catch block.
The below code will throw NullPointerException because we are doing some operations on a null String.
package com.javatrainingschool;
public class ExceptionExample {
public static void main(String[] args) {
String str = null;
String modifiedString = str.concat("xyz"); //this line will throw exception
System.out.println("Modified String is : " + modifiedString);
}
}
Output :
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.concat(String)" because "str" is null
at com.sks.ExceptionExample.main(ExceptionExample.java:10)
The problem when we don’t handle exceptions is that the program exists from the point where exception occur. The rest of the code from that line is not executed. This is the reason, modifiedString is not printed on the console. The program exists as soon as the exception occurs.
Using try-catch block, we can make the rest of the program still work. See the below example
package com.javatrainingschool;
public class ExceptionExample {
public static void main(String[] args) {
String str = null;
String modifiedString = null;
try {
modifiedString = str.concat("xyz"); //exception thrown here
} catch(NullPointerException npe) {
npe.printStackTrace();
}
System.out.println("Modified String is : " + modifiedString);
}
}
Output :
java.lang.NullPointerException: Cannot invoke "String.concat(String)" because "str" is null
at com.sks.ExceptionExample.main(ExceptionExample.java:10)
Modified String is : null
Example 2
The below example will throw ArithmeticException since divisor is 0. And we know, in mathematics, if we divide a number by zero, the result in indefinite. In Java, it throws ArithmeticException.
package com.javatrainingschool;
public class ExceptionExample {
public static void main(String[] args) {
int dividend = 123;
int divisor = 0;
int result = 0;
try {
result = dividend / divisor; //this line will throw exception
} catch(ArithmeticException e) {
System.out.println("Divisor cannot be zero.");
e.printStackTrace();
}
System.out.println(result);
}
}
Output :
Divisor cannot be zero.
java.lang.ArithmeticException: / by zero
at com.sks.ExceptionExample.main(ExceptionExample.java:11)
0
Example 3
The below exception will throw ArrayIndexOutOfBoundsException, since we are trying to access an element in the array which is beyond the size of the array.
package com.javatrainingschool;
public class ExceptionExample {
public static void main(String[] args) {
int [] arr = new int[] {10, 20, 30};
int lastElement = 0;
try {
lastElement = arr[4]; //exception occurs here
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Accessed element at index 4 is beyond the length of the array. Length of arr = " + arr.length);
e.printStackTrace();
}
System.out.println(lastElement);
}
}
Output :
Accessed element at index 4 is beyond the length of the array. Length of arr = 3
java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 3
0
at com.sks.ExceptionExample.main(ExceptionExample.java:11)
Multiple Catch blocks example
package com.javatrainingschool;
public class ExceptionExample {
public static void main(String[] args) {
int [] arr = new int[] {10, 20, 30};
int lastElement = 0;
int result = 0;
try {
result = 100 / 10;
lastElement = arr [result];
} catch(ArithmeticException e) {
System.out.println("Divisor cannot be zero.");
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Accessed element at index " + result + " is beyond the length of the array. Length of arr = " + arr.length);
e.printStackTrace();
}
System.out.println(lastElement);
}
}
Output :
Accessed element at index 10 is beyond the length of the array. Length of arr = 3
java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 3
at com.sks.ExceptionExample.main(ExceptionExample.java:13)
0
Multiple catch example with java 7
With java 7 and higher versions, there is a compact way of handling multiple exceptions using pipe ( | ) operator.
try {
result = 100 / 10;
lastElement = arr [result];
} catch(ArithmeticException | ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}