Exception Handling in Java with Examples

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

What is an Exception in Java

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

Arithmetic Exception Example

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.

NumberFormatException Handling

>javac 10 0

divisor should not be zero

This program validates the denominator is zero and then prints the message to user else performs 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 let’s 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 the above program to handle exceptions try and catch block is used.

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

The statements which can throw expectations are written inside the 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 an exception is thrown from code inside the try block.

In above program int c= a/b;

the exception is thrown when the value of b is zero so it should be inside the 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 the catch block and necessary action is performed inside the catch block.

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

Lets again execute the 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 a string so throwing the 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 let’s modify our code

again by compiling and running this code

>javac Division 10 a

Please enter valid number

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

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

here we used two try blocks and their corresponding catch blocks.

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

Let’s again change this code to handle multiple catches in a single try block.

Create your own exception: User-Defined exception in Java

Multiple catch blocks java

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

The exception is parent class for all exceptions.

Any exception thrown can handle by catching exceptions.

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

 Which of the following is not an advantage of Java exception handling?

 A. Java separates exception handling from normal processing tasks.
 B. Exception handling improves performance.
 C. Exception handling makes it possible for the caller’s caller to handle the exception.
 D. Exception handling simplifies programming because the error-reporting and error-handling code can be placed at the catch block.

Answer is B

More MCQ

Read More

  1. Exception Handling in Java: Hierarchy Example and Types
  2. Exception Handling try catch finally blocks in Java
  3. Throw and Throws Keywords in Java
  4. How To Fix Internal Exception: java.io.ioexception In Minecraft