In the previous tutorial, I have covered how to handle exceptions using try-catch blocks. In this guide, we will see how to handle multiple exceptions and how to write them in a correct order so that user gets a meaningful message for each type of exception.
Catching multiple exceptions
Lets take an example to understand how to handle multiple exceptions.
class Example{ public static void main(String args[]){ try{ int arr[]=new int[7]; arr[4]=30/0; System.out.println("Last Statement of try block"); } catch(ArithmeticException e){ System.out.println("You should not divide a number by zero"); } catch(ArrayIndexOutOfBoundsException e){ System.out.println("Accessing array elements outside of the limit"); } catch(Exception e){ System.out.println("Some Other Exception"); } System.out.println("Out of the try-catch block"); } }
Output:
You should not divide a number by zero Out of the try-catch block
In the above example, the first catch block got executed because the code we have written in try block throws ArithmeticException (because we divided the number by zero).
Now lets change the code a little bit and see the change in output:
class Example{ public static void main(String args[]){ try{ int arr[]=new int[7]; arr[10]=10/5; System.out.println("Last Statement of try block"); } catch(ArithmeticException e){ System.out.println("You should not divide a number by zero"); } catch(ArrayIndexOutOfBoundsException e){ System.out.println("Accessing array elements outside of the limit"); } catch(Exception e){ System.out.println("Some Other Exception"); } System.out.println("Out of the try-catch block"); } }
Output:
Accessing array elements outside of the limit Out of the try-catch block
In this case, the second catch block got executed because the code throws ArrayIndexOutOfBoundsException. We are trying to access the 11th element of array in above program but the array size is only 7.
What did we observe from the above two examples?
1. It is clear that when an exception occurs, the specific catch block (that declares that exception) executes. This is why in first example first block executed and in second example second catch.
2. Although I have not shown you above, but if an exception occurs in above code which is not Arithmetic and ArrayIndexOutOfBounds then the last generic catch handler would execute.
Lets change the code again and see 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 of try block"); } catch(Exception e){ System.out.println("Some Other Exception"); } catch(ArithmeticException e){ System.out.println("You should not divide a number by zero"); } catch(ArrayIndexOutOfBoundsException e){ System.out.println("Accessing array elements outside of the limit"); } System.out.println("Out of the try-catch block"); } }
Output:
Compile time error: Exception in thread "main" java.lang.Error: Unresolved compilation problems: Unreachable catch block for ArithmeticException. It is already handled by the catch block for Exception Unreachable catch block for ArrayIndexOutOfBoundsException. It is already handled by the catch block for Exception at Example.main(Example1.java:11)
Why we got this error?
This is because we placed the generic exception catch block at the first place which means that none of the catch blocks placed after this block is reachable. You should always place this block at the end of all other specific exception catch blocks.
Abhishek Bharat Parab says
Confusion about above example. If ArithmeticException, NullPointerException ArrayIndexOutOfBoundsException exception class are child of RuntimeExecption parent class, and these class is useful to handle runtime exception then why should it be followed by method declaration using throws keyword. since throws keyword is used to handle compile time exception.
Requesting your assistance for following queries :
1. If we can handle exceptions(checked/unchecked) using try/catch block, then why should we use throw or throws keyword in program with real time example?
2. Please tell me a situation where throw or throws keyword has to be used in program. please explain with an example
3. public void myMethod() throws ArithmeticException {
int division = 10/0 ;
step 1: new throw ArithmeticException(“cannot be divided by zero”);
}
In this example, If arithmeticException class is used to handle runtime exception, so why do we use it followed by throws keyword in method declaration?
does step 1 not sufficient to handle “divided by zero” exception?
I would be awaiting for your response respect to my queries
raghu says
keyword throw is used to define pre-defined/user defined exceptions
throws:
Actually all the possible exceptions must be handled by using try and catch block if we are not interested to handle checked exceptions atleast we need to make JVM to handle the checked exceptions by using keyword “throws” otherwise jvm will rise compile time error
throws is not exception handler it is an exception escaper.hence throws are not recommended in the industry programs which leads abnormal termination
Mithilesh Naik says
Hi Abhishek,
Answer o 1) usually you will see operations like these:
classA.methodA calls classB.methodB which again calls classC.methodC
class C returns something all the way to class A
(Only class A is allowed to interact to user)
in this case if exception occurs in class C then you throw it using
throw new your-exception //from code
or add “throws ExpectedException” in method signature of methodC
MethodC will throw it to methodB this should also have throws declaration. MethodB will throw it to methodA.
Method A will catch it in a catch block and do corresponding action
**This answers Q2**
Answer to 3)
in case 10/0 you dont need to throw exception explicitly. However say, your operation cannot support divide by 5 (assume). in this case do following
if (divisor ==5)
throw OperationNotSupported or throw ArithmeticException