Core Java - Exceptions Handling

What is an exception?

An Exception is an unwanted event that interrupts the normal flow of the program. When an exception occurs, program execution gets terminated. In such cases, we get a system generated error message.

The good thing about exceptions is that java developer can handle these exceptions in such a way so that the program doesn’t get terminated abruptly and the user gets a meaningful error message.

Why we use exception handling?

or

What is Exception Handling ?



The core advantage of exception handling is to maintain the normal flow of the application. An exception normally disrupts the normal flow of the application; that is why we need to handle exceptions. Let's consider a scenario:

  1. statement 1;  
  2. statement 2;  
  3. statement 3;  
  4. statement 4;  
  5. statement 5;//exception occurs  
  6. statement 6;  
  7. statement 7;  
  8. statement 8;  
  9. statement 9;  
  10. statement 10;  

Suppose there are 10 statements in a Java program and an exception occurs at statement 5; the rest of the code will not be executed, i.e., it will not execute statements 6 to 10. However, when we perform exception handling, the rest of the statements get executed. That is why we use exception handling.

Explain the Hierarchy of Exception classes.




All exception types are subclasses of class Throwable, which is at the top of the exception class hierarchy.

Types of Exceptions

In Java, exceptions broadly can be categories into checked exception, unchecked exception and error based on the nature of exception.

  • Checked Exception
  • The exception that can be predicted by the JVM at the compile time for example : File that need to be opened is not found, SQLException etc. These type of exceptions must be checked at compile time.

  • Unchecked Exception
  • Unchecked exceptions are the class that extends RuntimeException class. Unchecked exception are ignored at compile time and checked at runtime. For example : ArithmeticException, NullPointerException, Array Index out of Bound exception. Unchecked exceptions are checked at runtime.

  • Error
  • They typically ignore errors in code because we can rarely do anything about an error. For example, if stack overflow occurs, an error will arise. We cannot handle this type of error in the code.



 

Explain the class java.lang.Exception.

The parent class of all the exception classes is the java.lang.Exception class. 
The Exception class, it is a subclass of the built-in Throwable class. There is another subclass which is derived from the Throwable class i.e. Error as illustrated in Figure 1. The error can be defined as an abnormal condition that indicates something has gone wrong with the execution of the program. These are not handled by Java programs.

There are some important methods available in the Throwable class which are as follows:

  • public String getMessage() – Provides information about the exception that has occurred through a message, which is initialized in the Throwable constructor.
  • public Throwable getCause() – Provides root cause of the exception as represented by a Throwable object.
  • public void printStackTrace() – Used to display the output of toString() along with the stack trace to System.err (error output stream).
  • public StackTraceElement [] getStackTrace() – Returns an array with each element present on the stack trace. The index 0 element will symbolize the top of the call stack, and the last element of array will identify the bottom of the call stack.

There are mainly two types of exceptions in Java as follows:

  • Checked exception
  • Unchecked exception

How to Handle Exception?

A Java Exception is an object that describes the exception that may occur in a program. When exceptional events occur in java code, we say an exception to be thrown. The code that's responsible for doing something about the exception is called an exception handler.

Java provides controls using a special type of keywords to handle exception in the program. We list these keywords below.

  • try : This keyword is used to enclose the suspected code.
  • catch: This keyword acts as to enclose the exception handler code.
  • finally: It is used to execute the must have necessary code. Mostly used to clean-up the unused object references.
  • throw:This keyword is used to throw the exception object explicitly.
  • throws: We use this keyword to inform about the exceptions declared at the method declaration part.


Explain try and catch Block.

Try and catch both are Java keywords and used for exception handling. The try block is used to enclose the suspected code. Suspected code is a code that may raise an exception during program execution.

For example, if a code raise arithmetic exception due to divide by zero then we can wrap that code into the try block.


try{

  int a = 10;

  int b = 0

  int c = a/b; // exception

}

 The catch block also known as handler is used to handle the exception. It handles the exception thrown by the code enclosed into the try block. Try block must provide a catch handler or a finally block. We will discuss about finally block in our next tutorials.

The catch block must be used after the try block only. We can also use multiple catch block with a single try block.


try{

  int a = 10;

  int b = 0

  int c = a/b; // exception

}catch(ArithmeticException e){

  System.out.println(e);

}

 

try-catch Syntax

To declare try catch block, a general syntax is given below.


try{

  // suspected code

}catch(ExceptionClass ec){ 

// exception handler code.

}

Exception handling is done by transferring the execution of a program to an appropriate exception handler (catch block) when exception occurs.

Example: Handling Exception

Now lets understand the try and catch by a simple example in which we are dividing a number by zero. The code is enclosed into try block and a catch handler is provided to handle the exception.

class Excp

{

  public static void main(String args[])

  {

    int a,b,c;

    try

    {

      a = 0;

      b = 10;

      c = b/a;

      System.out.println("This line will not be executed");

    }

    catch(ArithmeticException e)

    {

      System.out.println("Divided by zero");

    }

    System.out.println("After exception is handled");

  }

}

 ------------------------ OUTPUT ----------------------

Divided by zero After exception is handled


Explanation

An exception will thrown by this program as we are trying to divide a number by zero inside try block. The program control is transferred outside try block. Thus the line "This line will not be executed" is never parsed by the compiler. The exception thrown is handled in catch block. Once the exception is handled, the program control is continue with the next line in the program i.e after catch block. Thus the line "After exception is handled" is printed.


Multiple catch blocks

A try block can be followed by multiple catch blocks. It means we can have any number of catch blocks after a single try block. If an exception occurs in the guarded code(try block) the exception is passed to the first catch block in the list. If the exception type matches with the first catch block it gets caught, if not the exception is passed down to the next catch block. This continue until the exception is caught or falls through all catches.

Multiple Catch Syntax

To declare the multiple catch handler, we can use the following syntax.

  
try  
  {  
   // suspected code
  }  
  catch(Exception1 e)  
  {  
    // handler code
  }   
catch(Exception2 e)  
{  
  // handler code
}  

  

Now lets see an example to implement the multiple catch block that are used to catch possible exception.

The multiple catch blocks are useful when we are not sure about the type of exception during program execution.

Examples for Multiple Catch blocks

In this example, we are trying to fetch integer value of an Integer object. But due to bad input, it throws number format exception.

  
class Demo{
  public static void main(String[] args) {
    try
    { 
      Integer in = new Integer("abc");
      in.intValue();
        
    } 
    catch (ArithmeticException e) 
    { 
      System.out.println("Arithmetic " + e); 
    } 
    catch (NumberFormatException e) 
    { 
      System.out.println("Number Format Exception " + e); 
    } 
  }
}
  

Number Format Exception java.lang.NumberFormatException: For input string: "abc"

In the above example, we used multiple catch blocks and based on the type of exception second catch block is executed.

Example: Multiple Exception

Lets understand the use of multiple catch handler by one more example, here we are using three catch handlers in catch the exception.

public class CatchDemo2
{  
  public static void main(String[] args) 
  {  
    try
    {    
      int a[]=new int[10];    
      System.out.println(a[20]);  
    }    
    catch(ArithmeticException e)  
    {  
      System.out.println("Arithmetic Exception --> "+e);  
    }    
    catch(ArrayIndexOutOfBoundsException e)  
    {  
      System.out.println("ArrayIndexOutOfBounds Exception --> "+e);  
    }    
    catch(Exception e)  
    {  
      System.out.println(e);  
    }                 
  }  
}

NOTE : At a time, only one exception is processed and only one respective catch block is executed.

Example for Unreachable Catch block

While using multiple catch statements, it is important to remember that sub classes of class Exception inside catch must come before any of their super classes otherwise it will lead to compile time error. This is because in Java, if any code is unreachable, then it gives compile time error.

class Excep
{
  public static void main(String[] args)
  {
    try
    {
      int arr[]={1,2};
      arr[2]=3/0;
    }
    catch(Exception e)    //This block handles all Exception
    {
      System.out.println("Generic exception");
    }
    catch(ArrayIndexOutOfBoundsException e)    //This block is unreachable
    {
      System.out.println("array index out of bound exception");
    }
  }
}

Generic exception


Nested try statement

try statement can be nested inside another block of try. Nested try block is used when a part of a block may cause one error while entire block may cause another error. In case if inner try block does not have a catch handler for a particular exception then the outer try catch block is checked for match.

class Excep
{
  public static void main(String[] args)
  {
    try
    {
      int arr[]={5,0,1,2};
      try
      {
        int x = arr[3]/arr[1];
      }
      catch(ArithmeticException ae)
      {
        System.out.println("divide by zero");
      }
      arr[4]=3;
    }
    catch(ArrayIndexOutOfBoundsException e)
    {
      System.out.println("array index out of bound exception");
    }
  }
}

divide by zero array index out of bound exception

Important points to Remember

  1. If you do not explicitly use the try catch blocks in your program, java will provide a default exception handler, which will print the exception details on the terminal, whenever exception occurs.
  2. Super class Throwable overrides toString() function, to display error message in form of string.
  3. While using multiple catch block, always make sure that sub-classes of Exception class comes before any of their super classes. Else you will get compile time error.
  4. In nested try catch, the inner try block uses its own catch block as well as catch block of the outer try, if required.
  5. Only the object of Throwable class or its subclasses can be thrown.

Java throw, throws and finally Keyword

Throw, throws and finally are the keywords in Java that are used in exception handling. The throw keyword is used to throw an exception and throws is used to declare the list of possible exceptions with the method signature. Whereas finally block is used to execute essential code, specially to release the occupied resources.

Now lets discuss each in details with the examples.

Java Throw

The throw keyword is used to throw an exception explicitly. Only object of Throwable class or its sub classes can be thrown. Program execution stops on encountering throw statement, and the closest catch statement is checked for matching type of exception.

Syntax :

throw ThrowableInstance

Creating Instance of Throwable class

We allows to use new operator to create an instance of class Throwable,

new NullPointerException("test");

This constructs an instance of NullPointerException with name test.

Example throw Exception

In this example, we are throwing Arithmetic exception explicitly by using the throw keyword that will be handle by catch block.

class Test
{
  static void avg()
  {
    try
    {
      throw new ArithmeticException("demo");
    }
    catch(ArithmeticException e)
    {
      System.out.println("Exception caught");
    }
 }

 public static void main(String args[])
 {
    avg();
 }
}

In the above example the avg() method throw an instance of ArithmeticException, which is successfully handled using the catch statement and thus, the program prints the output "Exception caught".

Java throws Keyword

The throws keyword is used to declare the list of exception that a method may throw during execution of program. Any method that is capable of causing exceptions must list all the exceptions possible during its execution, so that anyone calling that method gets a prior knowledge about which exceptions are to be handled. A method can do so by using the throws keyword.

Syntax:

type method_name(parameter_list) throws exception_list
{
  // definition of method
}

Example throws Keyword

Here, we have a method that can throw Arithmetic exception so we mentioned that with the method declaration and catch that using the catch handler in the main method.

class Test
{
  static void check() throws ArithmeticException
  {  
    System.out.println("Inside check function");
    throw new ArithmeticException("demo");
  }

  public static void main(String args[])
  {
    try
    {
      check();
    }
    catch(ArithmeticException e)
    {
      System.out.println("caught" + e);
    }
  }
}

Inside check function caughtjava.lang.ArithmeticException: demo


Difference between throw and throws

throwthrows
throw keyword is used to throw an exception explicitly.throws keyword is used to declare an exception possible during its execution.
throw keyword is followed by an instance of Throwable class or one of its sub-classes.throws keyword is followed by one or more Exception class names separated by commas.
throw keyword is declared inside a method body.throws keyword is used with method signature (method declaration).
We cannot throw multiple exceptions using throw keyword.We can declare multiple exceptions (separated by commas) using throws keyword.

finally clause

A finally keyword is used to create a block of code that follows a try block. A finally block of code is always executed whether an exception has occurred or not. Using a finally block, it lets you run any cleanup type statements that you want to execute, no matter what happens in the protected code. A finally block appears at the end of catch block.



Example finally Block

In this example, we are using finally block along with try block. This program throws an exception and due to exception, program terminates its execution but see code written inside the finally block executed. It is because of nature of finally block that guarantees to execute the code.

Class ExceptionTest
{
  public static void main(String[] args)
  {
    int a[] = new int[2];
    System.out.println("out of try");
    try
    {
      System.out.println("Access invalid element"+ a[3]);
      /* the above statement will throw ArrayIndexOutOfBoundException */
    }
    finally
    {
      System.out.println("finally is always executed.");
    }
  }
}

Out of try finally is always executed. Exception in thread main java. Lang. exception array Index out of bound exception.

You can see in above example even if exception is thrown by the program, which is not handled by catch block, still finally block will get executed.

Example : Finally Block

finally block executes in all the scenario whether exception is caught or not. In previous example, we use finally where exception was not caught but here exception is caught and finally is used with handler.

class Demo
{
  public static void main(String[] args)
  {
    int a[] = new int[2];
    try
    {
      System.out.println("Access invalid element"+ a[3]);
      /* the above statement will throw ArrayIndexOutOfBoundException */
    }
    catch(ArrayIndexOutOfBoundsException e) {
      System.out.println("Exception caught");
    }
    finally
    {
      System.out.println("finally is always executed.");
    }
  }
}

Exception caught finally is always executed.


User defined Exception subclass 

Java provides rich set of built-in exception classes like: ArithmeticException, IOException, NullPointerException etc. all are available in the java.lang package and used in exception handling. These exceptions are already set to trigger on pre-defined conditions such as when you divide a number by zero it triggers ArithmeticException.

Apart from these classes, Java allows us to create our own exception class to provide own exception implementation. These type of exceptions are called user-defined exceptions or custom exceptions.

You can create your own exception simply by extending java Exception class. You can define a constructor for your Exception (not compulsory) and you can override the toString() function to display your customized message on catch. Lets see an example.

Example: Custom Exception

In this example, we are creating an exception class MyException that extends the Java Exception class and

class MyException extends Exception
{
  private int ex;
  MyException(int a)
  {
    ex = a;
  }
  public String toString()
  {
    return "MyException[" + ex +"] is less than zero";
  }
}

class Demo
{
  static void sum(int a,int b) throws MyException
  {
    if(a<0)
    {
      throw new MyException(a); //calling constructor of user-defined exception class
    }
    else
    {
      System.out.println(a+b);
    }
  }

  public static void main(String[] args)
  {
    try
    {
      sum(-10, 10);
    }
    catch(MyException me)
    {
      System.out.println(me); //it calls the toString() method of user-defined Exception
    }
  }
}

MyException[-10] is less than zero

Example: Custom Exception

Lets take one more example to understand the custom exception. Here we created a class ItemNotFound that extends the Exception class and helps to generate our own exception implementation.


class ItemNotFound extends Exception
{
  public ItemNotFound(String s) {
    super(s);
  }

}

class Demo
{
  static void find(int arr[], int item) throws ItemNotFound
  {
    boolean flag = false;
    for (int i = 0; i < arr.length; i++) {
      if(item == arr[i])
        flag = true;
    }
    if(!flag)
    {
      throw new ItemNotFound("Item Not Found"); //calling constructor of user-defined exception class
    }
    else
    {
      System.out.println("Item Found");
    }
  }

  public static void main(String[] arts)
  {
    try
    {
      find(new int[]{12,25,45}, 10);
    }
    catch(ItemNotFound i)
    {
      System.out.println(i);
    }
  }
}

ItemNotFound: Item Not Found

Points to Remember

  1. Extend the Exception class to create our own exception class.
  2. We don't have to implement anything inside it, no methods are required.
  3. We can have a Constructor if we want.
  4. We can override the toString() function, to display customized message.

Comments

Popular posts from this blog

Advanced Java - JDBC

Core Java BCA3

Java Threads