Unit: 10 Exception Handling

By Haitomns G

The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so that the normal flow of the application can be maintained.

In this tutorial, we will learn about Java exceptions, it’s types, and the difference between checked and unchecked exceptions.

What is Exception in Java?

In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime. An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. There can be several reasons that can cause a program to throw exception. For example: Opening a non-existing file in your program, Network connection problem, bad input data provided by user etc.When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore, these exceptions are to be handled.

What is Exception Handling?

Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc. Exception handling is the process of handling errors and exceptions in such a way that they do not hinder normal execution of the program. For example, User divides a number by zero, this will compile successfully but an exception or run time error will occur due to which our applications will be crashed. In order to avoid this we should include exception handling techniques in our code.

Types of Java Exceptions

There are mainly two types of exceptions: checked and unchecked. An error is considered as the unchecked exception. However, according to Oracle, there are three types of exceptions namely:

  1. Checked Exception
  2. Unchecked Exception
  3. Error

1) Checked Exception

The classes that directly inherit the Throwable class except RuntimeException and Error are known as checked exceptions. For example, IOException, SQLException, etc. Checked exceptions are checked at compile-time.

2) Unchecked Exception

The classes that inherit the RuntimeException are known as unchecked exceptions. For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime.

3) Error

Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError, AssertionError etc.

Uncaught Exceptions

The UncaughtExceptionHandler is an interface inside a Thread class. When the main thread is about to terminate due to an uncaught exception the java virtual machine will invoke the thread’s UncaughtExceptionHandler for a chance to perform some error handling like logging the exception to a file or uploading the log to the server before it gets killed. We can set a Default Exception Handler which will be called for the all unhandled exceptions. It is introduced in Java 5 Version.

This Handler can be set by using the below static method of java.lang.Thread class.

public static void setDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHandler)

We have to provide an implementation of the interface Thread.UncaughtExceptionHandler, which has only one method.

Syntax

@FunctionalInterface

public interface UncaughtExceptionHandler {

   void uncaughtException(Thread t, Throwable e);

}

Example

public class UncaughtExceptionHandlerTest {

   public static void main(String[] args) throws Exception {

      Thread.setDefaultUncaughtExceptionHandler(new MyHandler());

      throw new Exception(“Test Exception”);

   }

   private static final class MyHandler implements Thread.UncaughtExceptionHandler {

      @Override

      public void uncaughtException(Thread t, Throwable e) {

         System.out.println(“The Exception Caught: ” + e);

      }

   }

}

Output

The Exception Caught: java.lang.Exception: Test Exception

Java try and catch

The try statement allows you to define a block of code to be tested for errors while it is being executed.

The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.

The try and catch keywords come in pairs:

Syntax

try {

            //  Block of code to try

}

catch(Exception e) {

             //  Block of code to handle errors

}

Example:

This will generate an error, because myNumbers[10] does not exist.

public class Main {

  public static void main(String[ ] args) {

    int[] myNumbers = {1, 2, 3};

    System.out.println(myNumbers[10]); // error!

  }

}

The output will be something like this:

Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 10

        at Main.main(Main.java:4)

If an error occurs, we can use try…catch to catch the error and execute some code to handle it:

Example

public class Main {

  public static void main(String[ ] args) {

    try {

      int[] myNumbers = {1, 2, 3};

      System.out.println(myNumbers[10]);

    } catch (Exception e) {

      System.out.println(“Something went wrong.”);

    }

  }

}

The output will be:

Something went wrong.

Finally

The finally statement lets you execute code, after try…catch, regardless of the result:

Example

public class Main {

  public static void main(String[] args) {

    try {

      int[] myNumbers = {1, 2, 3};

      System.out.println(myNumbers[10]);

    } catch (Exception e) {

      System.out.println(“Something went wrong.”);

    } finally {

      System.out.println(“The ‘try catch’ is finished.”);

    }

  }

}

The output will be:

Something went wrong.

The ‘try catch’ is finished.

The throw keyword

The throw statement allows you to create a custom error.The throw statement is used together with an exception type. There are many exception types available in Java: ArithmeticException, FileNotFoundException, ArrayIndexOutOfBoundsException, SecurityException, etc:

Example

Throw an exception if age is below 18 (print “Access denied”). If age is 18 or older, print “Access granted”:

public class Main {

  static void checkAge(int age) {

    if (age < 18) {

      throw new ArithmeticException(“Access denied – You must be at least 18 years old.”);

    }

    else {

      System.out.println(“Access granted – You are old enough!”);

    }

  }

  public static void main(String[] args) {

    checkAge(15); // Set age to 15 (which is below 18…)

  }

}

The output will be:

Exception in thread “main” java.lang.ArithmeticException: Access denied – You must be at least 18 years old.

        at Main.checkAge(Main.java:4)

        at Main.main(Main.java:12)

Java Catch Multiple Exceptions

Java Multi-catch block

A try block can be followed by one or more catch blocks. Each catch block must contain a different exception handler. So, if you have to perform different tasks at the occurrence of different exceptions, use java multi-catch block.

Points to remember

At a time only one exception occurs and at a time only one catch block is executed.

All catch blocks must be ordered from most specific to most general, i.e. catch for ArithmeticException must come before catch for Exception.

Example:

public class MultipleCatchBlock1 {

    public static void main(String[] args) {

        try {

            int a[] = new int[5];

            a[5] = 30 / 0;

        } catch (ArithmeticException e) {

            System.out.println(“Arithmetic Exception occurs”);

        } catch (ArrayIndexOutOfBoundsException e) {

            System.out.println(“ArrayIndexOutOfBounds Exception occurs”);

        } catch (Exception e) {

            System.out.println(“Parent Exception occurs”);

        }

        System.out.println(“rest of the code”);

    }

}

Output:

Arithmetic Exception occurs

rest of the code

Example 2:

public class MultipleCatchBlock2 {

    public static void main(String[] args) {

        try {

            int a[] = new int[5];

            System.out.println(a[10]);

        } catch (ArithmeticException e) {

            System.out.println(“Arithmetic Exception occurs”);

        } catch (ArrayIndexOutOfBoundsException e) {

            System.out.println(“ArrayIndexOutOfBounds Exception occurs”);

        } catch (Exception e) {

            System.out.println(“Parent Exception occurs”);

        }

        System.out.println(“rest of the code”);

    }

}

Output:

ArrayIndexOutOfBounds Exception occurs

rest of the code

Java Nested try block

In Java, using a try block inside another try block is permitted. It is called as nested try block. Every statement that we enter a statement in try block, context of that exception is pushed onto the stack.

For example, the inner try block can be used to handle ArrayIndexOutOfBoundsException while the outer try block can handle the ArithemeticException (division by zero).

Why use nested try block?

Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause another error. In such cases, exception handlers have to be nested.

Syntax:

….   

//main try block 

try   

{   

    statement 1;   

    statement 2;   

//try catch block within another try block 

    try   

    {   

        statement 3;   

        statement 4;   

//try catch block within nested try block 

        try   

        {   

            statement 5;   

            statement 6;   

     }   

        catch(Exception e2)   

        {   

//exception message 

        }   

    }   

    catch(Exception e1)   

    {   

//exception message 

    }   

}   

//catch block of parent (outer) try block 

catch(Exception e3)   

{   

//exception message 

}   

….  

Example:

public class NestedTryBlock {

    public static void main(String args[]) {

        // outer try block

        try {

            // inner try block 1

            try {

                System.out.println(“going to divide by 0”);

                int b = 39 / 0;

            }

            // catch block of inner try block 1

            catch (ArithmeticException e) {

                System.out.println(e);

            }

            // inner try block 2

            try {

                int a[] = new int[5];

                // assigning the value out of array bounds

                a[5] = 4;

            }

            // catch block of inner try block 2

            catch (ArrayIndexOutOfBoundsException e) {

                System.out.println(e);

            }

            System.out.println(“other statement”);

        }

        // catch block of outer try block

        catch (Exception e) {

            System.out.println(“handled the exception (outer catch)”);

        }

        System.out.println(“normal flow..”);

    }

}

Output:

image 4 1

Example 2:

public class NestedTryBlock2 {

    public static void main(String args[]) {

        // outer (main) try block

        try {

            // inner try block 1

            try {

                // inner try block 2

                try {

                    int arr[] = { 1, 2, 3, 4 };

                    // printing the array element out of its bounds

                    System.out.println(arr[10]);

                }

                // to handles ArithmeticException

                catch (ArithmeticException e) {

                    System.out.println(“Arithmetic exception”);

                    System.out.println(” inner try block 2″);

                }

            }

            // to handle ArithmeticException

            catch (ArithmeticException e) {

                System.out.println(“Arithmetic exception”);

                System.out.println(“inner try block 1”);

            }

        }

        // to handle ArrayIndexOutOfBoundsException

        catch (ArrayIndexOutOfBoundsException e4) {

            System.out.print(e4);

            System.out.println(” outer (main) try block”);

        } catch (Exception e5) {

            System.out.print(“Exception”);

            System.out.println(” handled in main try-block”);

        }

    }

}

Output:

image 4 2

Java Throws Keyword

The Java throws keyword is used to declare an exception. It gives an information to the programmer that there may occur an exception. So, it is better for the programmer to provide the exception handling code so that the normal flow of the program can be maintained.

Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked exception such as NullPointerException, it is programmers’ fault that he is not checking the code before it being used.

Syntax of Java throws

return_type method_name() throws exception_class_name{ 

//method code 

Advantage of Java throws keyword

Now Checked Exception can be propagated (forwarded in call stack).

It provides information to the caller of the method about the exception.

Example

import java.io.IOException; 

class Testthrows1{ 

  void m()throws IOException{ 

    throw new IOException(“device error”);//checked exception 

  } 

  void n()throws IOException{ 

    m(); 

  } 

  void p(){ 

   try{ 

    n(); 

   }catch(Exception e){System.out.println(“exception handled”);} 

  } 

  public static void main(String args[]){ 

   Testthrows1 obj=new Testthrows1(); 

   obj.p(); 

   System.out.println(“normal flow…”); 

  } 

Output:

exception handled

normal flow…

Difference between final, finally and finalize

The final, finally, and finalize are keywords in Java that are used in exception handling. Each of these keywords has a different functionality. The basic difference between final, finally and finalize is that the final is an access modifier, finally is the block in Exception Handling and finalize is the method of object class.

Along with this, there are many differences between final, finally and finalize. A list of differences between final, finally and finalize are given below:

Sr. no.Keyfinalfinallyfinalize
1.Definitionfinal is the keyword and access modifier which is used to apply restrictions on a class, method or variable.finally is the block in Java Exception Handling to execute the important code whether the exception occurs or not.finalize is the method in Java which is used to perform clean up processing just before object is garbage collected.
2.Applicable toFinal keyword is used with the classes, methods and variables.Finally block is always related to the try and catch block in exception handling.finalize() method is used with the objects.
3.Functionality(1) Once declared, final variable becomes constant and cannot be modified.
(2) final method cannot be overridden by sub class.
(3) final class cannot be inherited.
(1) finally block runs the important code even if exception occurs or not.
(2) finally block cleans up all the resources used in try block
finalize method performs the cleaning activities with respect to the object before its destruction.
4.ExecutionFinal method is executed only when we call it.Finally block is executed as soon as the try-catch block is executed. It’s execution is not dependant on the exception.finalize method is executed just before the object is destroyed.

Java final Example

Let’s consider the following example where we declare final variable age. Once declared it cannot be modified.

FinalExampleTest.java

public class FinalExampleTest {  

    //declaring final variable  

    final int age = 18;  

    void display() {  

    // reassigning value to age variable   

    // gives compile time error  

    age = 55;  

    }  

    public static void main(String[] args) {  

    FinalExampleTest obj = new FinalExampleTest();  

    // gives compile time error  

    obj.display();  

    }  

}  

Output:

image 4 3

In the above example, we have declared a variable final. Similarly, we can declare the methods and classes final using the final keyword.

Java finally Example

Let’s see the below example where the Java code throws an exception and the catch block handles that exception. Later the finally block is executed after the try-catch block. Further, the rest of the code is also executed normally.

FinallyExample.java

public class FinallyExample {    

      public static void main(String args[]){   

      try {    

        System.out.println(“Inside try block”);  

      // below code throws divide by zero exception  

       int data=25/0;    

       System.out.println(data);    

      }   

      // handles the Arithmetic Exception / Divide by zero exception  

      catch (ArithmeticException e){  

        System.out.println(“Exception handled”);  

        System.out.println(e);  

      }   

      // executes regardless of exception occurred or not   

      finally {  

        System.out.println(“finally block is always executed”);  

      }    

      System.out.println(“rest of the code…”);    

      }    

    }    

Output:

image 4 4

Java finalize Example

FinalizeExample.java

public class FinalizeExample {    

     public static void main(String[] args)     

    {     

        FinalizeExample obj = new FinalizeExample();        

        // printing the hashcode   

        System.out.println(“Hashcode is: ” + obj.hashCode());           

        obj = null;    

        // calling the garbage collector using gc()   

        System.gc();     

        System.out.println(“End of the garbage collection”);     

    }     

   // defining the finalize method   

    protected void finalize()     

    {     

        System.out.println(“Called the finalize() method”);     

    }     

}    

Output:

image 4 5

Java Custom Exception

In Java, we can create our own exceptions that are derived classes of the Exception class. Creating our own Exception is known as custom exception or user-defined exception. Basically, Java custom exceptions are used to customize the exception according to user need.

Consider the example 1 in which InvalidAgeException class extends the Exception class.

Using the custom exception, we can have your own exception and message. Here, we have passed a string to the constructor of superclass i.e. Exception class that can be obtained using getMessage() method on the object we have created.

Why use custom exceptions?

Java exceptions cover almost all the general type of exceptions that may occur in the programming. However, we sometimes need to create custom exceptions.

Following are few of the reasons to use custom exceptions:

  • To catch and provide specific treatment to a subset of existing Java exceptions.
  • Business logic exceptions: These are the exceptions related to business logic and workflow. It is useful for the application users or the developers to understand the exact problem.

In order to create custom exception, we need to extend Exception class that belongs to java.lang package.

Consider the following example, where we create a custom exception named WrongFileNameException:

public class WrongFileNameException extends Exception { 

    public WrongFileNameException(String errorMessage) { 

    super(errorMessage); 

    } 

Example:

// class representing custom exception 

class InvalidAgeException extends Exception {

    public InvalidAgeException(String str) {

        // calling the constructor of parent Exception

        super(str);

    }

}

// class that uses custom exception InvalidAgeException

public class TestCustomException1 {

    // method to check the age

    static void validate(int age) throws InvalidAgeException {

        if (age < 18) {

            // throw an object of user defined exception

            throw new InvalidAgeException(“age is not valid to vote”);

        } else {

            System.out.println(“welcome to vote”);

        }

    }

    // main method

    public static void main(String args[]) {

        try {

            // calling the method

            validate(13);

        } catch (InvalidAgeException ex) {

            System.out.println(“Caught the exception”);

            // printing the message from InvalidAgeException object

            System.out.println(“Exception occured: ” + ex);

        }

        System.out.println(“rest of the code…”);

    }

}

Output:

image 4 6

Also, Read

  1. Unit-4 Operator
  2. Unit-5 Control Statements
  3. Unit-6 Introducing Classes
  4. Unit: 7 A Closer Look at Methods and Classes
  5. Unit: 8 Inheritance
  6. Unit: 9 Packages and Interface

Haitomns G. is a desktop, android, and web developer based in Nepal. He has worked on building several websites, apps, and softwares for clients and independent projects. He is experienced in C, C++, C#, Java, Python, SQL, HTML, CSS, PHP, and JavaScript.

1 thought on “Unit: 10 Exception Handling”

  1. Keep up the good piece of work, I read few posts on this web site and I believe that your web blog is very interesting and has got circles of great information.

    Reply

Leave a Comment

Slide to prove you're not a bot/spammer *