In this article, we will look at how to catch a few exceptions, and how to write them in the correct order so that users get meaningful messages for each type of exception.
Catching a few exceptions
Let us take an example to understand how to deal with a few exceptions.
class Example {
public static void main (String args []) {
try{
int arr [] = new int [7];
arr [4] = 30/0;
System.out.println ( "Last Statement try block");
}
catch (ArithmeticException e) {
System.out.println ( "You do not have to divide a number by zero");
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println ( "Accessing array elements beyond the bounds");
}
catch (Exception e) {
System.out.println ( "Some other Exception");
}
System.out.println ( "Out of the try-catch block");
}
}
Output
You do not have to divide a number by zero
Out of the try-catch block
In the example above, the first catch block gets executed as code we have written to the try block throws ArithmeticException (because we divided that number by zero).
Now let's change the code a bit and see the change in the output:
class Example {
public static void main (String args []) {
try{
int arr [] = new int [7];
arr [10] = 10/5;
System.out.println ( "Last Statement try block");
}
catch (ArithmeticException e) {
System.out.println ( "You do not have to divide a number by zero");
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println ( "Accessing array elements beyond the bounds");
}
catch (Exception e) {
System.out.println ( "Some other Exception");
}
System.out.println ( "Out of the try-catch block");
}
}
Top comments (0)