Exception handling

  • Eclipse: Oxygen
  • Java: 1.8

Exception Handling is done to avoid errors which occur during the runtime of the program. Hence in such cases, we take care of such exceptions to prevent the program from ending abruptly.

A number of things can give rise to the following kinds of exceptions such as the file not found an error or any type of input type error where the datatype was different than expected or etc. We learn to avoid this and structure our program accordingly in this article.

Let’s look at the following example of exception handling in Java where we use a try-catch statement to handle the exception.

In this code, y! = 0 generates an exception if else that is handled by a try-catch block.

The keyword “try” is used to specify a block where we must place the exception code. A try block must be followed by a catch block, it means that we cannot use the try block alone.

The “catch” block is used to handle the exception, it must be preceded by the try block. It means that we cannot use the catch block alone.

Output

The value of y is 0

It shows multiple catch blocks for a single try block. It also shows the hierarchy of the exception classes. All the exceptions can be further classified into Throwable and Unchecked Exception which can be further classified into many more which will be seen forward.

If you have to perform different tasks in the appearance of different exceptions, use the Java multiple catch block.

Let’s see a simple example of the Java multiple catch block.

In the following program, the first catch block was executed because the code we wrote in the try block throws ArithmeticException (because we divided the number by zero).

Output

Arithmetic Exception occurred

This also explains the concept of a hierarchy of exception classes. This hierarchy, if it is not maintained, can be transformed into the code being unreachable at some points.

In the following code if the Exception catch block appears before the Arithmetic Exception Block then the latter will become unreachable as the Exception will catch all the thrown exceptions.

All catch blocks should be ordered from the most specific to the most general. The catch for ArithmeticException must come before the catch for Exception.

Output

Arithmetic Exception occurred

Contributed by: Poonam Tomar


Full stack Java Developer

   Buy me a coffee!

 

PayTM QR (INDIA)

Download file

Leave a Reply

avatar
  Subscribe  
Notify of
Close Menu