Exception Handling in Java

Category: Java   Tags: Java, Java Basic, Java Exception Handling

A Java exception object describe an exception/error that was caused by some Java code. Java exception handling allow us to catch and process the error thrown by our code.

Exceptions can be generated by the Java run-time system, or they can be manually generated by our code. Java exception handling is managed via five keywords: try, catch, throw, throws and finally.

How It Works?

Put the the piece of code that you want to monitor inside try block. If some exception occur inside the try block, it is thrown. You can catch this exception using catch and handle the exception as per your requirement. You can throw an exception manually using throw. A system generated exception is thrown by Java runtime. Here is syntax of a Java exception handling:

                            try {
                                // Java code that should be monitored
                            } catch(ExceptionType1 ob) {
                                // Exception handler for ExceptionType1 exception
                            } catch(ExceptionType2 ob) {
                                // Exception handler for ExceptionType2 exception
                            } finally {
                                // Here the code will always be executed after try block is finished
                            }
                        

Any exception that is expected to be thrown out of method should be mentioned using throws. A finally block is always executed even if any exception is thrown or not.

Exception Types

All exception types are subclasses of the built-in class Throwable. Throwable has two subclass: Exception and Error.

Exception defines the exception that a user program is expected to catch inside catch block. You can subclass this class to defined your own exception.

Exception of type Error are used by Java runtime system. Stack overflow is an example of such an error.

Examples

Here we show you the need of handling exception:

JavaExceptionSimpleExample.java

                            package com.tutorial.javabasic;

                            public class JavaExceptionSimpleExample {
                                public static void main(String s[]) {
                                    int a = 0;
                                    int b = 100/a;
                                    System.out.println("You can't reach this");
                                    System.out.println("I want to be printed");
                                }
                            }
                        

Here our target is to print the statement I want to be printed. Here we are trying to divide 100 by 0, which is obviously will not work and throws exception, therefore the statement System.out.println("You can't reach this"); and System.out.println("I want to be printed"); never get executed.

Once an exception is thrown the immediate statements are not executed and program will exit if no try-catch has been used. If you run this program it will show below exception:

                            Exception in thread "main" java.lang.ArithmeticException: / by zero
                        

Now we will use try-catch block:

JavaExceptionSimpleExample.java

                            package com.tutorial.javabasic;

                            public class JavaExceptionSimpleExample {
                                public static void main(String s[]) {
                                    try {
                                        int a = 0;
                                        int b = 100/a;
                                        System.out.println("You can't reach this");
                                    } catch(java.lang.ArithmeticException ex) {
                                        ex.printStackTrace();
                                    }
                                    System.out.println("I want to be printed");
                                }
                            }
                        

Output:

                            java.lang.ArithmeticException: / by zero
                            I want to be printed
                        

Here we have put our code inside try-catch block. As you can see that the statement System.out.println("You can't reach this"); still not print as an exception is thrown on line 7 and therefore rest statements are ignored. Inside catch block ex.printStackTrace(); is used to print the exception details.

The statement System.out.println("I want to be printed"); will get printed as we have already processed the exception and also it is after try-catch block.

Nested Catch Statement

A program can raise more than one exception. To handle this type of situation, you can write a nested catch statement. When you do this and if an exception is raised, each catch block is inspected in order. Whichever exception type matches first is executed and other catch statements are ignored.

JavaNestedCatchExceptionExample.java

                            package com.tutorial.javabasic;

                            public class JavaNestedCatchExceptionExample {
                                public static void main(String s[]) {
                                    try {
                                        String input = null;
                                        // String input = "hello world";
                                        String upperCaseString = input.toUpperCase();
                                        System.out.println("input is: " + upperCaseString);

                                        int a = 0;
                                        int b = 100/a;
                                        System.out.println("You can't reach this");
                                    } catch(NullPointerException ex) {
                                        System.out.println("NullPointerException found");
                                        ex.printStackTrace();
                                    } catch(java.lang.ArithmeticException ex) {
                                        System.out.println("ArithmeticException found");
                                        ex.printStackTrace();
                                    }
                                }
                            }
                        

Here, if input is null then the program will throw NullPointerException and therefore first catch block will be executed. So the output will be:

                            NullPointerException found
                            java.lang.NullPointerException
                                at com.tutorial.javabasic.JavaNestedCatchExceptionExample.main(JavaNestedCatchExceptionExample.java:7)
                        

If you change input to "hello world" the value of input will be printed but statement 100/a will throw ArithmeticException therefore second catch block will be executed. So the output will be:

                            input is: HELLO WORLD
                            java.lang.ArithmeticException: / by zero
                            ArithmeticException found
                                at com.tutorial.javabasic.JavaNestedCatchExceptionExample.main(JavaNestedCatchExceptionExample.java:11)
                        

Order of Nested Catch Statement

In a nested catch statement, a subclass catch block should always come before its superclass catch block. The reason is that a super class catch statement can catch any exception of its own type or any of its subclass type. Here is one example:

NestedCatchOrderExample.java

                            package com.tutorial.javabasic;

                            public class NestedCatchOrderExample {
                                public static void main(String s[]) {
                                    try {
                                        int a = 0;
                                        int b = 100/a;
                                        System.out.println("You can't reach this");
                                    } catch(Exception ex) {
                                        System.out.println("NullPointerException found");
                                        ex.printStackTrace();
                                    } catch(java.lang.ArithmeticException ex) {
                                        System.out.println("ArithmeticException found");
                                        ex.printStackTrace();
                                    }
                                }
                            }
                        

Exception is the superclass of all exception class therefore catch block for ArithmeticException exception will never be reached as its superclass catch block is already before it. So here you will get compile time error: exception ArithmeticException has already been caught

Nested Try Statement

In Java the try statement can also be nested. A try statement can be inside another try statement. If an inner catch block fails to catch an exception, the next catch block is inspected and it continue till the the last catch statement.

NestedTry.java

                            package com.tutorial.javabasic;

                            public class NestedTry {

                                public static void main(String s[]) {
                                    try {
                                        try {
                                            int a = 0;
                                            int b = 100 / a;
                                            System.out.println("You can't reach this");
                                        } catch (IllegalArgumentException ex) {
                                            System.out.println("IllegalArgumentException found");
                                            ex.printStackTrace();
                                        }
                                    } catch (java.lang.ArithmeticException ex) {
                                        System.out.println("ArithmeticException found");
                                        ex.printStackTrace();
                                    }
                                }
                            }
                        

In this Java program when 100/a is executed, an exception ArithmeticException is expected to be handle. So the program start evaluating each catch statement from inner catch block (IllegalArgumentException) to outer most catch statement and find its matching exception type ArithmeticException

Output:

                            ArithmeticException found
                            java.lang.ArithmeticException: / by zero
                                at com.tutorial.javabasic.NestedTry.main(NestedTry.java:9)
                        

throw

A throw statement is used to throw an exception explicitly. The general form of throw is:

                            throw ThrowableInstance;
                        

Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable only. The flow of execution stops immediately after the throw statement that mean any subsequent statements are not executed.

Once an exception is thrown, the nearest matching catch statement will be executed. Here is a simple Java program:

ThrowExample.java

                            package com.tutorial.javabasic;

                            public class ThrowExample {

                                public static void main(String s[]) {
                                    try {
                                        int a = 10;
                                        if (a < 100) {
                                            throw new IllegalArgumentException("Number is less than 100");
                                        }
                                    } catch (IllegalArgumentException ex) {
                                        System.out.println(ex.getMessage());
                                        ex.printStackTrace();
                                    }

                                }
                            }
                        

Output:

                            Number is less than 100
                            java.lang.IllegalArgumentException: Number is less than 100
                                at com.tutorial.javabasic.ThrowExample.main(ThrowExample.java:9)
                        

Here new IllegalArgumentException("Number is less than 100"); is used to create a Java exception object.

throws

A throws keyword in Java is used in the method declaration to indicate that this method might throw one of the listed type exceptions. So when the method is called, user should handle those exceptions. Below is the general syntax of throws:

                            type methodName(params) throws exceptionClass1, exceptionClass2,.., exceptionClassN {
                                // method body
                            }
                        

Here is one simple Java program that shows the need of throws:

ThrowsExample.java

                            package com.tutorial.javabasic;

                            public class ThrowsExample {

                                static void testThrows() {
                                    throw new IllegalAccessException("Catch me");
                                }

                                public static void main(String s[]) {
                                    testThrows();
                                }
                            }
                        

If you will try to run this code it will show compilation error:

                            Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - unreported exception java.lang.IllegalAccessException; must be caught or declared to be thrown
                                at com.tutorial.javabasic.ThrowsExample.testThrows(ThrowsExample.java:6)
                                at com.tutorial.javabasic.ThrowsExample.main(ThrowsExample.java:10)
                        

The solution to this problem is to add throws with testThrows() method declaration. Here is the correct version of above Java program:

ThrowsExample.java

                            package com.tutorial.javabasic;

                            public class ThrowsExample {

                                static void testThrows() throws IllegalAccessException {
                                    throw new IllegalAccessException("Catch me");
                                }

                                public static void main(String s[]) {
                                    try {
                                        testThrows();
                                    } catch (IllegalAccessException ex) {
                                        ex.printStackTrace();
                                    }
                                }
                            }
                        

Important thing to see here is that inside main() method also testThrows() has been wrap up in try-catch block. If any method throws any exception, the same exception should be thrown or catch wherever that method is being called.

finally

A finally block is always executed after try-catch block and also whether or not an exception is thrown. The finally block will execute even if no catch statement matches the exception.

FinallyBlockExample.java

                            package com.tutorial.javabasic;

                            public class FinallyBlockExample {

                                public static void main(String s[]) {
                                    try {
                                        System.out.println("I am just try");
                                    } finally {
                                        System.out.println("I am finally without catch");
                                    }
                                    try {
                                        int a = 0;
                                        int b = 100/a;
                                        System.out.println("You can't reach this");
                                    } catch(java.lang.ArithmeticException ex) {
                                        System.out.println("ArithmeticException found");
                                        ex.printStackTrace();
                                    } finally {
                                        System.out.println("I will be printed always.");
                                    }
                                }
                            }
                        

Output:

                            I am just try
                            I am finally without catch
                            java.lang.ArithmeticException: / by zero
                            ArithmeticException found
                            I will be printed always.
                                at com.tutorial.javabasic.FinallyBlockExample.main(FinallyBlockExample.java:13)
                        

Create Your Own Exception

Please have a look on this post Creating user defined Java exception.

Chained Exception

Please have a look on this post Java Chained Exception.