Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

Java – Exception Handling

In Java, while running a program if a program behaves abnormally (stops suddenly & unexpectedly) due to some abnormal event, it is said that exception has occurred.

Therefore, in short, we can say that an exception is an abnormal event that stops/terminates the program suddenly & unexpectedly during runtime.

The process of handling exceptions to avoid abnormal termination of the program is known as exception handling.

In Java language, an exception is an object that explains the abnormal event that occurs in the program at runtime.

Exception handling does not mean to solve the exception, but to provide the alternative way to prevent abnormal termination of a program due to the exception.

It is also possible to generate exceptions manually by a programmer along with Java runtime system.

Note

Exceptions occur only at runtime, not at compile time.

For a better understanding of exception & its handling let’s look at the real-life scenario.

While driving a car if a tire (tyre) got punctured (goes flat/ a blowout) then it is called an exception because it is an abnormal behavior of a tire and makes car stop while running (at runtime).

Java Programming Language Exception Handling

Generally, it is not possible to repair the punctured tire at the same time & place.

Therefore it is necessary to provide some alternative way to handle this type of situations (exceptions) that helps us to make our journey better & unstoppable.

Therefore generally most of us keep a spare tire in our car to handle this type of situations. This is known as exception handling.

Similarly, in Java, we provide an alternative way to handle abnormal conditions at runtime known as exception handling.

To handle exceptions Java has provided try block followed by the catch block, together known as try – catch block.

The code that may generate an exception is placed in try block & the exception generated in the try block is caught in the catch block.

Syntax for exception handling block

 try
{
    // code that may generate exception
}
 catch(ExceptionType e)
{
    // description of exception
}

Exception classes’ hierarchy

Java Programming Language Exception classes’ hierarchy

Throwable class is a superclass of all the exception types.

Exception without try-catch block

Now let’s see a program that generates an exception but does not have any way to handle it.

Example

class UncaughtException 
{
    public static void main(String args[])
    {
        int i = 10/0;
        System.out.println("Value of i = "+i);
    }
}

Output

Exception in thread "main" java.lang.ArithmeticException: / by zero
             at uncaught_exception.UncaughtException.main(UncaughtException.java:5)

Above program is not able to generate expected output because ArithmeticException has occurred at line,

int i=10/0;

and there is not any way to handle it.

The generated exception is called ArithmeticException because dividing any number by zero is not allowed in mathematics & it tries to override the arithmetic rules.

Since we have not used try-catch block to handle the exception, Java handles that occurred exception itself. This results in abnormal termination of the program.

Therefore it is better to handle exception using try-catch block to prevent abnormal termination of the program.

Exception caught using try-catch block

Here we have used try-catch block to handle exception manually. This prevents abnormal termination of the program, & program runs smoothly as if the exception had never occurred, as shown below:

class CaughtException 
{
    public static void main(String args[]) 
    {
        try
        {
            int i = 10/0;
            System.out.println("Value of i = "+i);
        }
        catch(ArithmeticException e)
        {
            System.out.println("Arithmetic exception caught");
        }
        System.out.println("Program running");
        System.out.println("Without abnormal termination");
    }
}

Output

Arithmetic exception caught
Program running
Without abnormal termination

Here Arithmetic Exception generated is handled manually by using a try-catch block.

The try-block contains the code that generates an Arithmetic Exception & catch-block handles it and describes the exception type that is handled.

Therefore abnormal termination of the program is prevented & rest of the program after try-catch block is executed normally.

The code after the line where the exception is generated is not executed.

In the above program, in the catch clause, we have used ArithmeticException class to handle the exception occurred in a try block.

It is also possible to handle the same exception by using Exception class instead of ArithmeticException class because Exception class is a superclass of an ArithmeticException class.

Exception class can handle all the exceptions of its type as well as its subclasses type.

Example

class CaughtException2 
{
    public static void main(String args[]) 
    {
        try
        {
            int i = 10/0;
            System.out.println("Value of i = "+i);
        }
        catch(Exception e)
        {
            System.out.println("Exception handled using "
                                   + "superclass of ArithmeticException class");
        }
        System.out.println("Program running");
        System.out.println("Without abnormal termination");
    }
}

Output

Exception handled using superclass of ArithmeticException class
Program running
Without abnormal termination

Try on a single statement

It is not possible to use try on a single statement.

The statement that needs to be protected by try block must be surrounded by curly braces.

Java Programming Language Try on a single statement Not Allowed

Note

Every statement used with a try, catch & finally must be surrounded by curly braces.

Various types of descriptions of an exception caught in catch block

In the catch block, the same exception can be described in various forms.

For example, let’s try for Arithmetic Exception.

i) By using printStackTrace() method

try
{
     int i = 10/0;
     System.out.println("Value of i = "+i);
}
catch(ArithmeticException e)
{
     e.printStackTrace();
}

Output

java.lang.ArithmeticException: / by zero
at caught_Exception.CaughtException.main(CaughtException.java:7)

ii) By using exception reference

try
{
    int i = 10/0;
    System.out.println("Value of i = "+i);
}
catch(ArithmeticException e)
{
    System.out.println(e); // calls toString() method
}

Output

java.lang.ArithmeticException: / by zero

iii) By using toString() method

try
{
    int i = 10/0;
    System.out.println("Value of i = "+i);
}
catch(ArithmeticException e)
{
    System.out.println(e.toString());
}

Output

java.lang.ArithmeticException: / by zero

iv) By using getMessage() method

try
{
    int i = 10/0;
    System.out.println("Value of i = "+i);
}
catch(ArithmeticException e)
{
    System.out.println(e.getMessage());
}

Output

/ by zero

 

Leave a reply