Exception Handling in Java – Exception Hierarchy & Catching Exceptions

Java exceptions are unexpected in a program, to remove them we must know how to deal with them. The process of dealing with these exceptions is known as Exception Handling in Java. Here, we will study the exception hierarchy and exception catching with examples.

Let’s start with the introduction to Exception in Java.

1. What is Java Exception?

Exception in Java is an unwanted event that occurs during the execution of any program when the compiler compiles the program, it changes the normal course of the program, and i.e. how the programmer wanted it to run.

An error and exception are totally different things, let us have a look at both of them-

  • Error – An error is not an exception by any means, but rather an issue that emerges outside the ability to control the user or the developer
  • Exception – An exception is can be handled, it is not that serious and a program may or may not want it.

2. Exception Handling in Java

As we studied, the process of dealing with the exception is called Exception Handling in Java. It will help you to maintain the flow of execution and get desired results.

A successful programmer is not s/he who can code, but s/he who can solve every hurdle faced along the way.

Let’s discuss with an example. Joe is going for a morning jogging; suddenly, he saw a big piece of rock in the middle of his way. This rock is an obstacle for Joe, how he will handle this situation. Joe changes his direction and passes through the rock, therefore, he gets over the hurdle. Exception Handling in Java is the same process.

JVM follows the same concept; if it finds something unsatisfactory, then, it throws an exception. And here the rock is an exception for Joe

Java Exception Handling with example

3. Exception Hierarchy in Java

All errors and exceptions in java belong to the subclass ‘Throwable’, which itself is a base class of the hierarchy. One branch head by error and other by exception, Java exception is the condition that the program should catch while errors should avoid. NullPointerException is an example of exception while StackOverflowError is an example of error.

Do you check the Difference Between Checked and Unchecked Exceptions in Java?

Exception Hierarchy in Java - Java Exception

4. Catching Exception in Java

To catch an exception we use a combination of a try-catch keyword. A try-catch is placed around the code which is expected to generate an error. The code inside try-catch is referred to as protected code. The syntax of try-catch is as follows:

Syntax –

try
  {
// Protected code
  }
catch (ExceptionName e1)
  {
// Catch block
  }

The code which will generate error is placed in the try block. When an exception occurs, then it handled by the catch block associated with it. Every try is followed either by a catch block or finally block.

Recommended Reading – Core Java vs Advanced Java

A catch statement declaring the type of exception that you are trying to catch. If an exception occurs in protected code i.e. in the try block, then the catch block is checked. If the type of exception is listed in a catch block, the exception is passed to the catch block as an argument.

Example –

package com.dataflair.multithreadingprogram;
public class tryCatchProgram
{
     public static void main(String args[])
     {
        try {
           int num[] = new int[10];
           System.out.println("Accessing the fifth element :" + num[5]);
        }
        catch (ArrayIndexOutOfBoundsException e) 
        {
           System.out.println("Exception thrown  :" + e);
        }
        System.out.println("Out of the block");
     }
  }

Output-try-catch-program-in-multithreading

4.1 Multiple Catch Blocks in Java

A try block can be followed by multiple catch blocks. We can have multiple catch block in Java too.

Don’t forget to study the Command Line Argument in Java.

The syntax of multiple catch block is as follows:

try
  {
// Protected code
  }
catch (ExceptionType1 e1)
  {
// Catch block
  }
catch (ExceptionType2 e2)
  {
// Catch block
  }
catch (ExceptionType3 e3)
  {
// Catch block
  }

The previous statements demonstrate three catch blocks, but you can have multiple catch blocks after a single try. If there is an exception in the protected code, then the exception is thrown to the first catch block in the list. In the code, ExceptionType1 matches the data type of the exception thrown, it gets caught there. If it doesn’t match then the exception passes down to the second catch statement. This will continue until the exception either is caught or falls through all catch statements.

4.2 The Throws/Throw Keywords in Java

If there is a method which does not handle a checked exception then it must be declared using throws keyword in Java. It appears at the end of a method’s signature.

We can throw an exception, by a newly instantiated one or an exception that you just caught, by using the throw keyword. Let us try to understand the difference between throws and throw keywords, throws are used to postpone the handling of a checked exception and throw is used to invoke an exception explicitly.

Example –

package com.dataflair.multithreadingprogram;

public class ThrowThrowsProgram {
  public void deposit(double amount) throws RemoteException {
    // Method implementation
    throw new RemoteException();
  }
  // Remainder of class definition
}

A method can throw more than one exception, the exceptions are declared in a list separated by commas. For example, the following method declares that it throws a RemoteException and InsufficientFundsException

Example –

package com.dataflair.multithreadingprogram;

public class ThrowThrowsProgram {
  public void withdraw(double amount) throws RemoteException,InsufficientFundsException {
    // Method implementation
  }
  // Remainder of class definition
}

4.3 The Finally Block in Java

The Finally is the block of code which always executes, irrespective of any exception. It allows us to run any statement no matter what happens to the code inside the try block.

A finally block has the following syntax −

try
{
   // Protected code
}
catch (ExceptionType1 e1)
{
   // Catch block
}
catch (ExceptionType2 e2)
{
   // Catch block
}
catch (ExceptionType3 e3)
{
   // Catch block
}
finally
{
   // The finally block always executes.
}

Example –

package com.dataflair.multithreadingprogram;
public class FinallyBlock 
{
  public static void main(String args[]) 
  {
    int num[] = new int[10];
    try 
    {
      System.out.println("Accessing the fifth element:" + num[5]);
    } 
    catch (ArrayIndexOutOfBoundsException e) 
    {
      System.out.println("Exception thrown  :" + e);
    }
    finally 
    {
      num[0] = 6;
      System.out.println("The value of First element is: " + num[0]);
      System.out.println("The finally statement is always executed");
    }
  }
}

Output-

Finally-block-in-java

5. Summary

Now you know the ways of handling an exception handling in Java with examples. In addition, we have covered the working of the exception hierarchy along with its examples. We have also discussed the try-catch statements to catch the exception.

If you have any confusion related to Exception Handling in Java. Feel free to share with us!

Next article in the Java DataFlair tutorial series – Detect Deadlock in Java.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.