How to Handle Exception in Java

An Exception is an event that occurs during the exception of the program and disrupts the normal executions. In recent posts, we have seen what can be the causes of exception and how it breaks the normal flow of executions. In this post, we will see How to handle exception in java.

handle exception in java

There are few keywords that are used in exception handling in Java. These keywords will you help to understand How to handle exceptions in java?
1. try
2. catch
3. finally
4. throw
5. throws

Let’s start with the basic example and then move to advance topics. The try block and catch block is the first step to handle any type of exception. In the try block, we put the code that can be the reason for the exception.
Suppose we are dividing numbers then we should put the code in a try block because there may be a chance the divisor can be 0. If any exception occurs in the try block, the try block takes the control and through on catch block.

try 
{
  // block of code that can throw exceptions
} catch (Exception ex)
{
  // Exception handler
}

We can’t use try block without catch or finally block.

After through the exception by try block, now catch block comes in the role. The catch block catches the exception and takes the appropriate action on the exception. We can have any number of catch blocks.

try 
{
  // block of code that can throw exceptions
} catch (ExceptionType1 ex1)
{
  // exception handler for ExceptionType1
} catch (ExceptionType2 ex2)
{
  // Exception handler for ExceptionType2
} 

The code that we want to execute irrespective of the occurrence of an exception is put in a Finally block. It means the Finally block always executes whether the exception occurs or not. In other words, a Finally block is executed in all circumstances. This block is used to perform mandatory operations like close the connection.

try
{
// block of code that can throw exceptions
}
catch (ExceptionType1 ex1)
{
// exception handler for ExceptionType1
}
finally
{
//Mandatory code
}

How to handle null pointer exception in java

Whenever we perform any operation on null, the compiler throws the NullPointerException exception. Suppose you have a two-string and you want to check the equality of two strings. But there is one string holding null and another holding value.

public  class ExceptionHandling 
{
	public static void main(String[] args) 
    {
	  String str1 = null;
	  String str2 = "Hello";
	  boolean isEqual = str1.equals(str2);
	  System.out.println("Are they equals: "+isEqual);
	  System.out.println("Bye");
    }
}

Output: Exception in thread “main” java.lang.NullPointerException
at ExceptionHandling.main(ExceptionHandling.java:7)

Here you can see the program is showing NullpointerException. It is not showing any output when it encountered null and breaks the flow of execution. Let’s see how we can handle it.

We can pull this code try block and handle o flow of execution.

public  class ExceptionHandling 
{
	public static void main(String[] args) 
    {
	  String str1 = null;
	  String str2 = "Hello";
	  boolean isEqual = false;
	  try
	  {
		  isEqual = str1.equals(str2);
	  }
	  catch(NullPointerException e)
	  {
		  System.out.println("There is null string");
	  }
	  System.out.println("Are they equals: "+isEqual);
	  System.out.println("Bye");
    }
}

Output: There is null string
Are they equals: false
Bye

How an Exception Handled by JVM

Default Exception Handling: If any exception has occurred in the method then the method creates an Object known as Exception Object and this object will be handled by JVM. When a method creates an Exception object and hands over it to JVM it’s called throwing an Exception. This Exception object holding all the details about exceptions like name, description of exception, and retain the state of the program where an exception occurred. There may be a chance when multiple exceptions occurred in different methods. This ordered list of the methods is called Call Stack.

Now here is the procedure that will happen.

  • First, the run-time system finds the method in the call stack that has an Exception handler. Through exception handler, if any method contains a block of code that can handle the occurred exception.
  • The run-time system starts searching which methods were called. It means the run-time system tries to find the caller.
  • If it finds any handler for a thrown exception(a type of the exception object thrown matches the type of the exception which used in handler).
  • If the run time system(JVM) doesn’t find the appropriate handler then the default exception handler will handle the exception, which is part of the run-time system. It prints the exception and terminates the program abnormally.

1 thought on “How to Handle Exception in Java”

Leave a Comment