In this article we will discuss what is an exception in Java and how to handle exception in Java.

What is an exception in Java

An error occurred at runtime in a Java Application is called an Exception. If a triggered Exception is not handled then it will cause the application to crash.

Checkout following code,

Above example will crash abruptly with following output,

That’s because String reference strObj was set to null and a member function was called with it. Hence a runtime error occurred and an exception was thrown i.e. NullPointerException. But this code didn’t handle the triggered exception and application crashed.

How to handle an exception in Java

When an exception will occur then an Exception class Object will be created and Java Runtime will search for its handler.

 

Code for which we want to handle the triggered exception must be in try block i.e.

Now exception triggered inside the try block should be handled by a catch block after it i.e.

When an exception occurs then Runtime will search of its Exception Handler i.e a catch block. First of all it will search in the current function where exception has occurred.

Exception Handling in Current Function:

Let’s see, how we can catch the exception in previous example by enclosing the code in try block and handling the exception in catch block i.e.

Output:

Here, NullPointerException was catched in the same function and handled accordingly. From the line where exception is triggered execution flow of program will move to catch block directly. It means lines after that will not be executed, as shown in above example.

Handling Exception in Parent Functions

Here code that triggered the exception was in try block and catch block was in the same function. But what if there is appropriate handler in the function where exception has occurred?

If Java Runtime does not find any handler in function where exception has triggered, then it will search in its parent function from the call stack and search will go on till it finds any handler or main function is reached. If it reaches the main() function and still find no handler then it will make the application to crash.

Let’s see how to handle exception in parent function,

Output

 

Here exception was handled in the parent function.

Click Here to Subscribe for more Articles / Tutorials like this.