Exception Handling in Java

Exception Handling in Java

In this article, I am going to discuss Exception Handling in Java with Examples. Whenever we develop any application there is a chance of occurring errors in the application. As a Java developer, it is our key responsibility to handle the exception while developing an application. At the end of this article, you will understand the following pointers in detail.

  1. What is an Error?
  2. Compile Time and Run time Errors
  3. What is an Exception?
  4. Why an exception occurs?
  5. What happens when an exception is raised in the program?
  6. What JVM does when a logical mistake occurred in the program?
  7. Exception Hierarchy in Java
  8. What are the differences between Error and Exception?
  9. Types of Exceptions in Java
  10. Checked and Unchecked Exceptions in Java
  11. What is exception handling in Java?
  12. Why we need Exception Handling in Java?
  13. How can we handle an exception in Java?
  14. Multiple catch blocks in Java
  15. Can we catch all exceptions using a single catch block?
  16. When should we write multiple catch blocks for a single try block?
  17. How to display Exception or Runtime Error Message?
What is an Error?

An Error indicates a serious problem that a reasonable application should not try to catch. We have the following two types of errors:

  1. Compile Time Error
  2. Run Time Error
Compile Time Error

Errors that occur at the time of compilation of the program are called as compile-time errors. Compile-time errors occurred because if we don’t follow the java syntaxes properly, java programming rules properly, etc. Compile-time errors are identified by java compiler.

So in the simple word we can say that compile-time errors occur due to the poor understanding of the programming language. These errors can be identified by the programmer and can be rectified before the execution of the program only. So these errors do not cause any harm to the program execution.

Run Time Error

Errors that occur at the time of execution in the program are called as runtime errors. Run-Time Errors are also called as Exceptions. Exceptions may occur because of programmer logic fails or JVM fails. Exceptions are identified by JVM.

Note: The Runtime errors are dangerous because whenever they occur in the program, the program terminates abnormally on the same line where the error gets occurred without executing the next line of code.

What is an Exception?

Exceptions are the run time errors that occur during the execution of the program. The exception will cause the abnormal termination of the program execution. An Exception is an unwanted event that interrupts the normal flow of the program. When an exception occurs program execution gets terminated. It is an object which is thrown at runtime.

Why an exception occurs?

These errors occurred when we entering wrong data into a variable, trying to open a file for which there is no permission, trying to connect to the database with the wrong user id and password, the wrong implementation of logic, missing of required resources, etc.

There can be several reasons that can cause a program to throw an exception. For example: Opening a non-existing file in your program, Network connection problem, bad input data provided by the user, etc.

What happens when an exception is raised in the program?

Program execution is terminated abnormally. It means statements placed after exception causing statements are not executed but the statements placed before that exception causing statements are executed by JVM.

What JVM does when a logical mistake occurred in the program?

It creates an exception class object that is associated with that logical mistake and terminates the current method execution by throwing this exception object by using the “throw” keyword. So we can say an exception is an event that occurs during the execution of a program that disrupts the normal flow of instruction execution.

Example: The below example shows program execution without exception
public class ExceptionHandlingDemo
{
 public static void main(String[] args) 
 {
  int a =20;
  int b = 10;
  System.out.println("a value = " + a);
  System.out.println("b value = " + b);
  int c = a/b;
  System.out.println("c value = " + c);
 }
}

Output:

Java program execution without exception

Example: The following example shows program execution with the exception
public class ExceptionHandlingDemo
{
 public static void main(String[] args) 
 {
  int a =20;
  int b = 0;
  System.out.println("a value = " + a);
  System.out.println("b value = " + b);
  int c = a/b;
  System.out.println("c value = " + c);
 }
}

Output:

Java program execution with exception

Explanation of the above Program:

After printing the value of a and b, JVM terminates this program execution by throwing ArithmeticException because the logical mistake we committed is dividing integer number by integer zero. As we know it is not possible to divide an integer number by zero. But it is possible to divide a number with double zero (0.0).

From the above program, we can define the exception technically as

  1. An exception is an event because when an exception is raised JVM internally executes some logic to prepare that exception related messages.
  2. The exception is a signal because by looking into exception message developer will take necessary actions against that exception.
  3. An exception is an object because for throwing exception JVM or we should create an appropriate class object.
Exception Hierarchy in Java

The java.lang.Throwable class is the root class of Java Exception hierarchy which is inherited by two subclasses: Exception and Error. All exception and error types are subclasses of class Throwable, which is the base class of the hierarchy. One branch is headed by Exception. This class is used for exceptional conditions that user programs should catch. NullPointerException is an example of such an exception. Another branch, Error is used by the Java run-time system(JVM) to indicate errors having to do with the run-time environment itself(JRE). StackOverflowError is an example of such an error. A hierarchy of Java Exception classes are given below:

Exception Hierarchy in Java

Here,

Object: Object is the super most class of all classes available in java.

Throwable: For all types of exception java.lang.Throwable is the superclass. It has two main subclasses

  1. Error
  2. Exception

Exception: Exception is super most class of all exceptions which may occur because of programmer logic failure. These exceptions we can handle.

Error: Error is the super most class of all exceptions that occur because of JVM failure. These errors we cannot handle.

What are the differences between Error and Exception?

An Exception is an exception that can be handled. It means when an exception happens the programmer can do something to avoid any harm. But an Error is an exception which cannot be handled. It means it happens and the programmer cannot do anything. Let see in details

Difference 1:

Error type exception is thrown due to the problem occurred inside JVM logic, like If there is no memory in the java stack area to create a new Stackframe to execute method then the JVM process is killed by throwing Error type exception “java.lang.StackOverfolwError”. If there is no memory in the heap area to create a new object then the JVM process is killed by throwing Error type exception “java.lang.OutOfMemoryError”.

Exception type exceptions are thrown due to the problem occurred in java program logic, like If we divide an integer number with zero, then JVM terminates program execution by throwing Exception type exception “java.lang.ArithmeticException”. If we pass the array size as a negative number, then JVM terminates the program execution by throwing the exception type exception “java.lang.NegativeArraySizeException”.

Difference 2:

We cannot catch Error type exception because error type exception is not thrown in our application and once this error type exception is thrown JVM is terminated.

We can catch Exception type exception because exception type exception is thrown in our program and moreover JVM is not directly terminated because of exception type exception. JVM is only terminated if the thrown exception is not caught.

Types of Exceptions in Java:

We have the following two types of Exceptions:

  1. Checked Exceptions
  2. Unchecked Exceptions
Checked Exceptions in Java:

Exceptions that identified at compilation time and occurred at runtime are called checked exceptions. These checked exceptions are also called as Compile Time Exceptions.

An exception said to be checked exception whose exception handling is mandatory as per the compiler. Example: IOException, ClassNotFoundException, CloneNotSupportedException, etc.

Unchecked Exceptions in Java

Exceptions that identified and occurred at run-time are called Unchecked Exceptions. These Unchecked Exceptions are also called as Runtime Exceptions.

An exception is said to be unchecked exception whose exception handling is optional as per the compiler. Example: Arithmetic Exception, NumberFormatException, NoSuchMethodError, etc.

Note: All child classes of Error and Runtime Exception classes are called the unchecked exception and remaining classes are called checked exceptions.

Example of getting clarity about the exception:

Check below program, in this program, there is a chance of raising three exception

public class Division
{
 public static void main(String[] args) 
 {
  int a = Integer.parseInt(args[0]);
  int b = Integer.parseInt(args[1]);
  int c = a/b;
  System.out.println("Result : " + c);
 }
}

Output:

Checked and unchecked Exceptions in Java

Is the above exception messages are user understandable?

Definitely no, users cannot understand the above exception messages because they are java based exception messages. So the user cannot take further decisions alone to resolve the above problem. Developers should guide to solve the above problem.

What is the solution for the above problem?

It is the developer’s responsibility to convert java exception messages into user understandable message format. To solve this problem developer should write exception handling code in java program. Using exception handling code, developers can catch the exception and can print and pass user understandable messages.

What is exception handling in Java?

The process of catching the exception for converting JVM given exception message to end-user understandable message or for stopping the abnormal termination of the program is called exception handling.

The process of handling these run time errors or exceptions is called as Exception Handling. Once we handle the exception in a program we will be getting the following advantages

  1. We can stop the abnormal termination
  2. We can perform any corrective action that may resolve the problem occurring due to abnormal termination.
  3. Displaying a user-friendly error message, so that the client can resolve the problem provided if it is under his control.
Why we need Exception Handling in Java?

In projects, the exception is handled

  1. To stop the abnormal termination of the program
  2. To provide user understandable messages when an exception is raised. So that users can take decisions without the developer’s help.

Basically by implementing Exception handling, we are providing life to a program to talk to the user on behalf of the developer.

What is the procedure to Handle Exception in Java?

The Exception Handling in Java is a 4 steps procedure

  1. Preparing the exception object appropriate to the current logical mistake.
  2. Throwing that exception to the appropriate exception handler.
  3. Catching that exception
  4. Taking necessary actions against that exception
How can we handle an exception in Java?

There are two ways to handle the exception in Java.

  1. Logical implementation
  2. Try catch implementation
What is logical implementation?

In this method, we handle the exception by using logical statements. In real-time programming, the first and foremost importance always given to logical implementation only. If it is not possible to handle the exception using logical implementation then we only need to go for try-catch implementation.

import java.io.*;
public class Main
{
  public static void main (String[]args) throws IOException
  {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));	
        int a, b, c;
        System.out.println("Enter Any 2 Numbers");
        a =  Integer.parseInt(br.readLine());
        b =  Integer.parseInt(br.readLine());
        if (b == 0)
        {
            System.out.println("second number should not be zero");
        }
        else
        {
            c = a / b;
            System.out.println("C VALUE = " + c);
        }
    }
}

Output:

logical implementation to handle exception in Java

In the above example when we entered the second number is zero, then the exception will be raised and that is handled using logical implementation. But while we are entering two numbers instead of the number if we entered any character then it will give you one exception that is FormatException which is not handled in this program as shown in the below image.

logical implementation to handle exception in Java

Whenever an exception has occurred within the particular method then corresponding exception object is created by the particular method and given to JVM, then JVM will search for exception handling code within the particular method if not available it will search in its caller method even there also it is not available, then finally JVM will call “Default Exception Handler” Program which will display the Exception object and terminate the method from java stack (abnormal termination). In order to handle such type of exception, we need to go for Try catch implementation.

Exception handling in Java using the Try Catch implementation

In Java, Exception Handling can be done by using five Java keywords:

  1. Try
  2. Catch
  3. Finally
  4. Throw
  5. throws

Let us first understand how try-catch works and then we will proceed for the rest three keywords.

Try block:

try keyword establishes a block in which we need to write the exception causing and its related statements. That means exception causing statements must be placed in the try block so that we can handle and catch that exception for stopping abnormal termination and to display end-user understandable messages.

Catch block:

The catch block is used to catch the exception that is thrown from its corresponding try block. It has logic to take necessary on that caught exception. Catch block syntax is look like a constructor. It does not take accessibility modifier, normal modifier, return type.

It takes a single parameter of type Throwable or its subclasses. Throwable is the superclass of all exception sub-classes. Inside catch block, we can write any statement which is legal in java including raising an exception. A try block can be followed by multiple catch blocks. 

Syntax to use Try Catch in Java:

Exception handling in Java using the Try Catch implementation

Below program shows handling and catching exceptions to print user understandable messages relevant to the thrown exception.

import java.io.*;
public class Main
{
  public static void main (String[]args) throws IOException
  {
    try
    {

        BufferedReader br =
         new BufferedReader (new InputStreamReader (System.in));
        int a, b, c;
        System.out.println ("Enter Any 2 Numbers");
        a = Integer.parseInt (br.readLine ());
        b = Integer.parseInt (br.readLine ());
        
        c = a / b;
        System.out.println ("C VALUE = " + c);
    }
    catch (ArithmeticException ae)
    {
      System.out.println ("please dont pass the second value as 0");
    }
  }
}

Output:

Exception handling in Java

Rules in using try Catch in java

Rule1: try must follow either zero or n number of catch blocks or 1 finally block else it leads to Compilation Error: “try without a catch or finally”

Rule2: catch must be placed immediately after try block else it leads to Compilation Error: “catch without try:”

Rule3: finally must be placed either immediately after try or after try/catch else it leads to Compilation Error: “finally without try”

Rule4: the catch block parameter must be of type java.lang.Throwable or its sub-classes else it leads to Compilation Error: “incompatible types”

Rule5: try/catch/finally blocks are not allowed at the class level directly because logic is not allowed at the class level directly.

Multiple catch blocks in Java:

It is possible in Java to write multiple catch blocks for a single try block. Check the below program.

import java.io.*;
public class Main
{
  public static void main (String[]args) throws IOException
  {
    try
    {
        BufferedReader br =
         new BufferedReader (new InputStreamReader (System.in));
        int a, b, c;
        System.out.println ("Enter Any 2 Numbers");
        a = Integer.parseInt (br.readLine ());
        b = Integer.parseInt (br.readLine ());
        
        c = a / b;
        System.out.println ("C VALUE = " + c);
    }
    catch (NumberFormatException nfe)
    {
      System.out.println ("please pass only integer values");
    }
    catch (ArithmeticException ae)
    {
      System.out.println ("please dont pass the second value as 0");
    }
  }
}

Output:

Multiple catch blocks in Java

Note: After the try block, we can write multiple catch blocks to catch every exception thrown from its corresponding try block.

Can we catch all exceptions using a single catch block?

Yes, we can catch all exceptions with a single catch block with parameter “java.lang.Exception” We should use this catch block only for stopping abnormal termination irrespective of the exceptions thrown from its corresponding try block. An example is given below.

import java.io.*;
public class Main
{
  public static void main (String[]args) throws IOException
  {
    try
    {
        BufferedReader br =
         new BufferedReader (new InputStreamReader (System.in));
        int a, b, c;
        System.out.println ("Enter Any 2 Numbers");
        a = Integer.parseInt (br.readLine ());
        b = Integer.parseInt (br.readLine ());
        
        c = a / b;
        System.out.println ("C VALUE = " + c);
    }
    catch (Exception ex)
    {
      System.out.println (ex.getMessage());
    }
  }
}

Output:

Can we catch all exceptions using a single catch block?

It is always recommended to write catch blocks with exception parameters even though we are writing multiple catch blocks. It acts as a backup catch block.

When should we write multiple catch blocks for a single try block?

We should write multiple catch blocks for a single try block because of the following reasons

  1. To print message specific to an exception or
  2. To execute some logic specific to an exception

In our multiple catch block programs, we have placed catch blocks with different exception classes to print messages relevant to the caught exception.

Rules for Writing Multiple catch block in java:

Rule1: catch block should not be duplicated.

Rule2: superclass parameter catch block should not be placed before the child class parameter catch block.

Violation any of the above rules leads to CE: “exception has already been caught

Note: we write multiple catch blocks not only for printing exception specific messages also for executing some logic specific to the exception raised in the corresponding try statement.

Example: using multiple catch block along with generic catch block
import java.io.*;
public class Main
{
  public static void main (String[]args) throws IOException
  {
    try
    {
        BufferedReader br =
         new BufferedReader (new InputStreamReader (System.in));
        int a, b, c;
        System.out.println ("Enter Any 2 Numbers");
        a = Integer.parseInt (br.readLine ());
        b = Integer.parseInt (br.readLine ());
        
        c = a / b;
        System.out.println ("C VALUE = " + c);
    }
    catch (NumberFormatException nfe)
    {
      System.out.println ("please pass only integer values");
    }
    catch (ArithmeticException ae)
    {
      System.out.println ("please dont pass the second value as 0");
    }
    catch (Exception ex)
    {
      System.out.println ("Generic Exception");
    }
  }
}

Output:

multiple catch block along with generic catch block in java

How to display Exception or Runtime Error Message?

The throwable class has three methods to print the exception messages. These methods are useful when we write catch blocks with a superclass as a parameter. JVM printed Exception message format is shown below.

How to display Exception or Runtime Error Message?

Using printStackTrace():

If we use the printstackTrace() method it will display the Exception information in detail like reason, Exception class name, program name where it has occurred, in what method, in what line.

Using printStackTrace()

Using toString():

If we use the toString() method it will display the reason why Exception has occurred and the Exception class name.

Using toString()

Using getMessage():

If we use the getMessage() method it will display only the reason why Exception has occurred.

Using getMessage()

Below example shows calling above three methods:
public class Main
{
  public static void main (String[]args)
  {
    try
    {
      System.out.println (10 / 0);
    }
    catch (ArithmeticException ae)
    {
      System.out.println ("getMessage  method output");
      System.out.println (ae.getMessage ());
      System.out.println ("toString method output");
      System.out.println (ae.toString ());
      System.out.println ("printStackTrace() method output");
      ae.printStackTrace ();
      System.out.println ("JVM default output");
      throw ae;
      //by using above statement we are just re-throwing the caught exception this 
      //exception is caught by JVM default handler and prints full exception messages 
      //along with thread name
    }
  }
}

Output:

How to display Exception or Runtime Error Message

In the next article, I am going to discuss the need and use of Java Finally block with examples. Here, in this article, I try to explain Exception Handling in Java with examples. I hope you enjoy this Exception Handling in Java with Examples article. I would like to have your feedback. Please post your feedback, question, or comments about this Exception Handling in Java with Examples article.

Leave a Reply

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