Exception Handling in Java

Exception Handling in Java with Examples

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 Java developers, 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 do 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 do 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 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 the java compiler. So in simple words, we can say that compile-time errors occur due to a 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 runtime errors. Run-Time Errors are also called Exceptions. Exceptions may occur because 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 enter the wrong data into a variable, try to open a file for which there is no permission, try to connect to the database with the wrong user id and password, the wrong implementation of logic, missing 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 do 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:

program execution without exception in java

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:

program execution with exception in java

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 numbers 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 the exception message developer will take necessary actions against that exception.
  3. An exception is an object because for throwing an exception, JVM or we should create an appropriate class object.
Exception Hierarchy in Java

The java.lang.Throwable class is the root class of the 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 is 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 exceptions java.lang.Throwable is the superclass. It has two main subclasses

  1. Error
  2. Exception

Exception: Exception is the super most class of all exceptions that 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 that cannot be handled. It means it happens and the programmer cannot do anything. Let’s see in detail

Difference 1:

Error type exception is thrown due to the problem that 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 the Error type exception “java.lang.OutOfMemoryError”.

Exception type exceptions are thrown due to the problem that 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 an Error type exception because an error type exception is not thrown in our application and once this error type exception is thrown JVM is terminated.

We can catch an Exception type exception because an exception type exception is thrown in our program and moreover JVM is not directly terminated because of an 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 are identified at compilation time and occurred at runtime are called checked exceptions. These checked exceptions are also called 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 are identified and occurred at run-time are called Unchecked Exceptions. These Unchecked Exceptions are also called Runtime Exceptions. An exception is said to be an 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 the remaining classes are called checked exceptions.

Example of getting clarity about the exception:

Check the 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:

Unchecked Exceptions in Java

Is the above exception messages user-understandable?

Definitely, no, users cannot understand the above exception messages because they are java based on 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 to 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 the 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 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 do 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:

What is logical implementation

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 which is FormatException which is not handled in this program as shown in the below image.

Exception handling in Java using the Try Catch implementation

Whenever an exception has occurred within the particular method then the 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 a type of exception, we need to go for Try catch implementation.

Exception handling in Java using the Try Catch implementation with Examples

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 with 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, or return type.

It takes a single parameter of type Throwable or its subclasses. Throwable is the superclass of all exception sub-classes. Inside the 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

Exception Handling Example in Java

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:

handling and catching exceptions to print user understandable messages

Rules in using try Catch in java
  1. 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”
  2. Rule2: catch must be placed immediately after try block else it leads to Compilation Error: “catch without try:”
  3. Rule3: finally must be placed either immediately after try or after try/catch else it leads to Compilation Error: “finally without try”
  4. Rule4: the catch block parameter must be of type java.lang.Throwable or its sub-classes else it leads to Compilation Error: “incompatible types”
  5. 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 the 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 a 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:
  1. Rule1: catch block should not be duplicated.
  2. Rule2: superclass parameter catch block should not be placed before the child class parameter catch block. Violation of any of the above rules leads to CE: “exception has already been caught
  3. Note: we write multiple catch blocks not only for printing exception-specific messages but also for executing some logic specific to the exception raised in the corresponding try statement.
Example: using multiple catch blocks 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:

using multiple catch block along with generic catch block

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, and in what line.

Using printStackTrace()

Using toString():

If we use the toString() method it will display the reason why the 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 the Exception has occurred.

Using getMessage()

Below example shows calling the 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:

Exception Handling in Java with examples

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 *