Handling Multiple Exceptions.

Handling Multiple Exceptions:

During writing a program, there may arise chances of getting multiple exceptions while executing a program. So, it is the duty of programmer to handle these exceptions. Exceptions occurring more than one are called as Multiple Exceptions.

Multiple Exceptions can be handled by writing multiple catch block in a program.

ADVERTISEMENT

Now, let us understand, how to handle multiple exceptions in the following program.

In the below program of handling multiple exceptions, there are two exceptions.

1. Arithmetic Exception                    2. ArraysIndexOfBoundsExceptions

💡So, we will use two catch blocks to handle the exceptions or to display the reason behind the exceptions as described in following program.
public class Test
{
public static void main(String[] args) {
try {
//in this block statements having exceptions are written

int x = 15;
int y = 0;
int c = x / y;
System.out.println(c); //this is an arithmetic exception

//creating an array
int arr[] = {5, 10, 15};
arr[13] = 20;
// this will through an error as given below.
            // Exception in thread "main"
            //java.lang.ArrayIndexOutOfBoundsException:
            //Index 13 out of bounds for length 3
}
//creating a catch block to handle these multiple exceptions
catch(ArithmeticException e)
{
System.out.println("Any number can't be divided by 0.");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Please check arrays index is within range");
}
}
}
Output:
Any number can't be divided by 0.
Please check arrays index is within range

Modification to above code:

You can also use the one catch block to display the reason behind errors. Want to know how? Let us see.

We can catch more than one exception in same catch block. This can be achieved using "OR" operator (|)
public class Test
{
public static void main(String[] args) {
try {
//in this block statements having exceptions are written

int x = 15;
int y = 0;
int c = x / y;
System.out.println(c); //this is arithmetic exception

//creating an array
int arr[] = {5, 10, 15};
arr[13] = 20;
}
//creating a catch block to handle these multiple exceptions
catch(ArithmeticException | ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
}
}

Also Read:


Previous Post Next Post

Contact Form