Exception handling in Java

Exception Handling in java

To learn about exception handling first you must know what is an exception

An exception is run time error that can occur due to wrong user input or due to logical error in programming.

Consider a simple example.

Take two integer number from command prompt and divide the number.

The code is

We complice above program

c:\> javac   division.java

while running this program we will pass

two values to program as below

  > java division 10 2

Above two values 10 and 2 known as command  line argument these values are accessed in string [] s.

There s is string array  first value 10 is stored in s[0] and second value is stored in s[1]

S is string array so we converted these string values to integer by calling Integer.parseInt(value)

Here Integer is a class and parseInt is static method used to convert string value to int value.

The converted value is stroed in a and in b

The result of division operation is

                                C= a/b;   //c = 10/2 =5 

It will store value 5 in c.

  Next statement print division is 5

This is our desired result.

What happen if user enters value 10 and 0.

What happen if user enters value 10 and 0.

  Then the statement

                                C= a/b; // c= 10/0 –

   This statement throw arithmetic exception.

    The output is a below.

Exception in thread “main” java.lang.ArithmeticException: / by zero
at division.main(division.java:5)

The above exception is due to Wrong user input.

To handle above situation we can use user input validation or exception handling.

Lets see user input validation here before division operation check whether the value of b is zero or not.

If it is zero information to user and stop the program else perform the division as below.

>javac 10 0

divisor should not be zero

This program validate the denominator is zero then print message to user else perform division operation.

Here validation is used to avoid the exception. This is good practice to validate user input to avoid exceptions.

Here we want to learn exception handling so lets see the above program with java exception handling

lets run again above code

>java Division 10 2

Division is 3

>java Division 10 0

Arithmetic Exception

In above program to handle exception try and catch blocked is used.

Inside try block the code is written which can throw exception.

The statements which can throw expection is written inside try block.

To catch the exception a catch block is used with exception type . inside the catch block appropriate exception handling is done.

Catch block executes when exception is thrown from code inside try block.

In above program int c= a/b;

exception is thrown when the value of b is zero so it should be inside try block.

The statement System.out.println(“division is “ + c); is not throwing an exception it is also inside the try block.

If division statement throw an exception. The control is passed to catch block and necessary action is performed inside catch block.

The catch block is only executed if statements inside try block throws an exception.

Lets again execute above program with value 10 and String value lets a 

>javac Division 10 a

Exception in thread "main" java.lang.NumberFormatException: For input string: "a" at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at division.main(division.java:4)

Here second value is string so throwing above exception

Integer.parseInt (s[1]) throw an exception  because it is unable to convert string to int.

In our program we handled only arithmetic exception

To handle this exception lets modify our code

again compiling and running this code

>javac Division 10 a

Please enter valid number

System.exit(1) is used to exit from program.

Here denominator is not a number so no need to continue the program.

here we used two try block and its corrosponding catch blocks.

If you want we can use one try block and multiple catch block.

Lets again change this code to handle multiple catch in single try block.

Here all type of exceptions are checked in try block when an exception is thrown based on exception a catch block is executed.

Exception is parent class for all exceptions.

Any exception thrown can handle by catching exception.

Standing multiple exceptions in program, then general exception should be last catch statement otherwise specific exception catch statement will not reached.

Finally Keyword in Java

In java exception handling, any code that we want to must be execute put inside the finally block.

After the execution of try and catch block, finally block executes. try block must be used with either catch or finally, or with both.

Normally when exception occurs then further programs never executes. 

But either exception occurs or not, in both condition finally block executes.

Example1:  write a program to demonstrate the use of finally block with only try.

In the above program, we use two conditions, in the first condition we set array a is “a[100] = 20;”

 than exception occurs the following two lines will never execute

System.out.println(“Never Execute”);

System.out.println(“After try/finally “);

But finally block executes. And output is:

In the second condition, we set array a is “a[5] = 10;”  than there is no exception occurs.

use finally block executes. The output is:

Note: In this program, we have not used catch block, means when an exception will be generated then the program will never execute but finally must be executed .

Example2: write a program to demonstrate the use of finally block with try catch.

In the above program, we uses two condition, in the first condition we set array a is “a[100] = 20;”  than exception occurs the following  line will not execute

            System.out.println(“Never Execute”);

and exception is thrown which is caught bycatch(ArrayIndexOutOfBoundException  e)” after the catch rest of the program will execute. and the output is:

Java Throws Keyword

In a java programming, throws keyword list the type of exception that a method might throw.

In the throws clause, we declare all the exception that a method can throw.



Here, exception1, exception2 are comma, list of the exception that a method can throw.


Explaination: We throws NullPointerException in the line “throw new NullPointerException(“demo”);” .

Here we set “demo” is a name of thread.

This line “throw new NullPointerException(“demo”);” throw the exception which is handled by catch block associated with try within main().

Throw Keyword in Java

In java programming, If the exception occurs within try block it is thrown.

A system generate exception is automatically thrown by java run time system but if we want to  manually thrown an exception, we can do so by using throw keyword. 


           throw    ThrowableInstance;

here, ThrowableInstance must be an object of type Throwable or subclass of Throwable.

Example: write a program to demonstrate throw keyword.

Note:  In this program new is used to create an instance of NullPointerException and we get two chance to deal with the same error.

In the line  “throw new NullPointerException(“demo”);” 

throw keyword is used to throw  NullPointerException(“demo”). Here we set “demo” is a name of exception.

This NullPointerException(“demo”) catch by catch() method which resides in a demo() method.

 Line “throw e;”  re-throw the exception which is catch by catch() method which resides in a main() method.


try catch blocks in Java

Que. Write a program to create a arithmetic exception and handle whit try catch block.


Exception occurs at the line “a = 42 / d; “ , then this exception is thrown, program control transfer from  try block to catch block.

Once  catch block has executed program control continue with the next line in a program following entire try/catch statement.

In the line “catch (ArithmeticException e) “  e is a reference of exception “ArithmeticException”.

When we print the value of “e “ it will print  ( java.lang.ArithmeticException:/by zero                                                                    at  Test.main(Test.java:6) )

  • ArithmeticException is an exception class which resides in java.lang package.
  • “/by zero”  is a type of arithmetic exception (divided by zero).
  • “Test” is the name of the class.
  • “main” is a method in which an exception occurs.
  • 6 is line number in which exception occured.

Multiple catch Clause

In java programming, when within a try block multiple exception occurs than for handling those multiple exception we use multiple catch with single try block.

When we pass no command line argument (during run time) than the length of command line argument (args.length) is zero means value of variable “a” is 0.

Than the output is:

When we pass one or more command line argument ( in this program one command line argument is passed “test” during run time) than the length of command line argument (args.length) is one means value of variable “a” is  1.

Than the output is:

Unreachable Code:

In Java programming, in a sequence of catch statement exception subclass must come before its super class.

In a series, if exception super class comes before  its subclass than exception sub class would never be reached.

It is known as unreachable code. In Java programming, unreachable code is an compile-time error.    

Example : Write a program to demonstrate unreachable code.

Note: If we will try to compile this program we will receive an error message stating that the second catch statement is unreachable because ArithmeticException is a subclass of Exception class . 

     Then the first catch statement will handle all exception based error, including Arithmetic Exception therefore second catch statement will never execute.

 To solve the problem, reverse the order of catch statement.  

Nested try statement

In java programming, it is possible to create a try block within another try block. Such try block is known as nested try.


If there is no command line argument present then the output.

If there is no command line argument present then the output.

Types of Exceptions

In java programming, Exception class is a subclass of class Throwable.

Apart from Exception class, class Error is also derived from class Throwable.

Error: In java programming, error is Unrecoverable. It occurs during compile time.

For example, if we write wrong syntax then error will generate during compile time.

There are two types of Exception

  1. Checked Exception
  2. Unchecked Exception

Checked Exception

Here is the list of some checked exception

  1. IllegalAccessException: in java programming, this exception occurs when access to a class is denied.
  2. ClassNotFoundException: this exception occurs when class not found.
  3. NoSuchMethodException : when a requested method dose not exist this exception occurs.
  4. CloneNotSupportedException: in java programming,If you are trying to use the clone method in a classwhere Cloneable interface is not implemented, it throwsCloneNotSupportedException. Clone() method is used to create exactcopy of a object
  5. InterruptedException : in java, when we work with multiple threads then one thread  interrupts another thread.  
Exception Hierarchy

Unchecked Exception

  1. ArithmeticException : in java programming this exception, represent the arithmetic error, such as divided-by-zero.
  2. IndexOutOfBoundsException: when some type of index is out of bounds this exception occur.
    • ArrayIndexOutOfBoundsException: in java programming this exception represent the Array index is out of bound. This condition is arises when we try to access illegal array index.
    • StringIndexOutOfBoundsException : in java programming, when we access the index outside the bound of string than this exception occurs.
  3. NegativeArraySizeException: when array is created with negative size than this exception is arises.
  4. NullPointerException: in java programming this exception occurs when invalid use of null reference.
  5. IllegalThreadStateException: this exception occurs , when required operation not compatible with current thread state.