Java Exception Handling: Try, Catch & Finally | 2023

In this article, we will discuss Java’s exception handling mechanism. An exception is an abnormal state at the time of execution, or we can say that at runtime.

We need to handle these exceptions so the normal flow of the program is maintained. There is no automatic system to handle exceptions. Therefore, we have to manage them manually with a piece of code.

What are Exceptions and their types?

An Exception can be defined as an event that occurs during the execution of the program. Formally, those type of errors that disrupts the normal flow of the program is known as Exceptions.

There are two types of Exceptions which are discussed below :

Types of Exceptions in Java
Types of Exceptions in Java

Built-in Exception in Java

Exceptions that are already provided by Java libraries are defined as built-in exceptions. It can be divided into two parts.

Checked Exception

Those Exceptions which occur at the compile-time of the program is known as Checked Exceptions. The programmer must handle the situation if this type of exception arises; otherwise, the system has shown a compilation error.

These types of Exceptions are caught at compile time by Java Runtime System.

Example of Checked Exceptions

  • ClassNotFoundException(Arises due to put the wrong class name in code)
  • SQLException(Arises due to writing the wrong syntax query).

Unchecked Exception

The unchecked exceptions can be assumed opposite of the checked exceptions.

These type of Exceptions occurs when our program is correct according to the syntax but logically incorrect.

In this type of Exception, no compiler error generates, Because the compiler can catch syntax errors not logical ones.

Example of Unchecked Exception

  • ArrayIndexOutOfBoundsExceptions(Occurs when trying to access wrong indices of an array)
  • ArithmeticException( When we try to divide a number by zero, Then this exception generates)

Fundamentals of Exception Handling

A Java exception can be defined as an object that describes an exceptional (that is, error) a condition that has occurred in a programme.

When an exception arises, an object is created according to the exception and thrown in the method that caused the error.

An exception can be handled by the Java Runtime System, or we can handle it manually via a piece of code to maintain the flow of the programme.

In Java, the following five keywords are crucial for handling exceptions: try, catch, throw, throws, and finally.

We will discuss all of these five keywords soon. Before that, let’s see the general format programme with exception handling keywords in Java :

package newPackage;
import java.util.*;	
public class BeeTechnical
{
	  public static void main(String[] args)
	  {
		  try
		  {
        	     //Block of code to monitor for errors
                  }
                  catch(ArithmeticException e1)
		  {
        	      //This block will execute if Arithmetic Exception occurred	 
                  }
                  catch(NullPointerException e2)
                  {
                      //This block will execute if NullPointer Exception occurred        	  
                  }
                  finally 
                  {
                      //Block of code to be execute when try block ends     	  
                  }	
      }      
}
  • Try Block: The code which can generate an error during runtime is put inside the Try Block. Formally, the code we want to monitor for the exception is contained within the Try Block.
  • Catch Block: Catch block contains the piece of code needed to execute when a particular type of exception arises. When the execution heads with an exception, Then the flow of the programme turns towards the suitable Catch Block, Which can handle the occurred exception. So that the normal flow of the programme is maintained.
  • Finally Block: Finally block contains the piece of code, Which is important like closing a file, closing the connection, and closing the Scanner(Used to take input in Java). It doesn’t matter whether an exception occurred or not Finally Block always executes. Therefore, It contains the essential line of codes that needs to be executed always.
  • Throw: Throw is a keyword in Java to throw an exception manually and Use inside a method . We throw the exception manually by making an object of that class with which the exception is related.
  • Throws: Any Exception we want to throw out of a method must be specified as such by a throws clause with a suitable Exception class. There is no need to create an object of that class with which the exception is related.

Use of Try-Catch Block with an Example :

package newPackage;
import java.util.*;	
public class BeeTechnical
{
	  public static void main(String[] args)
	  {
		  try
		  {
                   int a = 5;
                   int b = 0;
                   System.out.println(a/b);
                  }
                    catch(ArithmeticException e)
		  {
        	  System.out.println("Catch Block Executed");
        	  System.out.println(e);
          }		
      }
       
}

In the programme above the code that can contain exceptions is put inside the Try Block.

As we can clearly see that integer 5 is divided by 0 in the code inside the try block, Which will generate ArithmeticException.

Therefore, We defined the catch block containing an object of ArithmeticException class. This catch block will handle the situation When an arithmetic exception will occur. The Output of the programme will be as follows :

Output :

Divide by Zero Exception in Java
Divide by Zero Exception in Java

The “Catch Block Executed” line in the output indicates the flow of the programme moved towards the catch block when Arithmetic Exception(number 5 divided by 0) is caught at runtime. The second line of output shows us the type of exception and from which class it relates.

Use Multiple Catch Blocks in Java

package newPackage;
import java.util.*;	
public class BeeTechnical
{
	  public static void main(String[] args)
	  {
		  try
		  {
               int arr[] = new int[0];
               System.out.println(arr[1]);
          }
          catch(ArithmeticException e)
		  {
        	  System.out.println("Catch Block with Arithmetic Exception Executed");
        	  System.out.println(e);
          }	 catch(ArrayIndexOutOfBoundsException e)
		  {
        	  System.out.println("Catch Block with Index Out Of Bounds Exception Executed ");
        	  System.out.println(e);
          }			
      }
       
}

Code contains two catch blocks, One having the object of ArithmeticException class and Another having ArrayIndexOutOfBoundsException class’s object.

In the code above array, arr[] of 0 sizes is initialized but we are trying to access its first index, Which doesn’t exist. Therefore, The code will generate an ArrayIndexOutOfBounds Exception.

Which will be handled by the catch block having the object of ArrayIndexOutOfBounds.

If the exception is of type Arithmetic, Then the Catch block having an object of ArithmeticException will execute. Formally, We can define multiple catch clauses for monitoring a code, If any type of Exception occurs, Then it will be handled by the suitable catch block having the object of same as the exception type that occurred.

Use of Finally Block in Java

In Java, Finally Block is a block which contains the piece of code that must be executed regardless of the exception. Formally, It doesn’t matter whether a code for monitoring contains an Exception or not Finally Block will always execute.

Let’s try to understand its use in Java code.

Finally Block Example, When there is no Exception :

Code :

package newPackage;
import java.util.*;	
public class BeeTechnical
{
	  public static void main(String[] args)
	  {
		  try
		  {
               int a = 10;
               int b = 5;
               System.out.println("A divided by B is : "+(a/b));
          }
          catch(ArithmeticException e)
		  {
        	  System.out.println("Catch Block with Arithmetic Exception Executed");
        	  System.out.println(e);
          }	
		  finally {
			  System.out.println("Programme Executed Successfully");
		  }
      }
       
}

We can see in the code above that “Programme Executed Successfully” is inside the Finally Block. The code we are monitoring has no issues, We can clearly see that variable A will divide by B successfully and will not generate any ArithmeticException. Let’s see the output of the code :

Output :

Java Finally block,when there is not exception
Java Finally block,when there is not exception

As we have no Exception in our monitored code the Finally Block executes by printing the line “Programme Executed Successfully” in the output. Now let us see the second case for Finally Block.

Finally Block Example, When there is an Exception :

package newPackage;
import java.util.*;	
public class BeeTechnical
{
	  public static void main(String[] args)
	  {
		  try
		  {
               int a = 10;
               int b = 0;
               System.out.println("A divided by B is : "+(a/b));
          }
          catch(ArithmeticException e)
		  {
        	  System.out.println("Catch Block with Arithmetic Exception Executed");
        	  System.out.println(e);
          }	
		  finally {
			  System.out.println("Programme Executed Successfully");
		  }
      }
       
}

We changed the value of variable B in code with 0, Which will generate an ArithmeticException at the time of dividing A by B. Let’s see the output in this case.

Output :

ArithmeticException in Java
ArithmeticException in Java

We can see in that the line “Programme Executed Successfully” is printed again in the output. When monitored code contains an Exception.

Therefore, We can clearly see that the Execution of the Finally Block doesn’t depend upon the occurrence of an Exception, It will always execute, No matter monitored code contains exception or not.

Use of Throw in Java With an Example

The throw keyword is used to throw an Exception manually. This keyword is used inside the method having some condition of occurring an Exception. Let’s see the use of the throw keyword with an example.

	package newPackage;
	import java.util.*;	
	public class BeeTechnical
	{
		  public static void main(String[] args)
		  {
			  try
			  {
	               int a = 10;
	               int b = 0;
	               DivideFunction(a, b);
			  }
			  finally
			  {
				  System.out.println();
			  }
	      }
		  static int DivideFunction(int a, int b)
			{
				 if(b==0)
		         {
		      	   throw new ArithmeticException("Number Divided by Zero Exeception");
		         }
		         else {
		      	   return a/b;
		         }
			}
	       
	}
	

In the code above we defined a function DivideFunction to divide an integer A with another integer B. We know it that if a number is divided by 0. Then, an Arithmetic type Exception occurs.

Therefore, We mentioned this condition inside the If-Block of the function. Inside the if block, We are creating an object of ArithmeticException class using new Keyword and throwing the Exception using the throw keyword manually.

Output :

How to use throw keyword in Java
How to use throw keyword in Java

In the output, the same Arithmetic Exception is generated, That we are throwing using the throw keyword.

Use of Throws Keyword in Java with an Example

Any Exception we want to throw out of a method must be specified as such by a throws clause with a suitable Exception class. There is no need to create an object of that class with which the exception is related. We just need to mention the Exception class of Exception, That has a chance to occur.

Code :

	package newPackage;
	import java.util.*;	
	public class BeeTechnical
	{
		  public static void main(String[] args)
		  {
			  try
			  {
	               int a = 10;
	               int b = 0;
	               DivideFunction(a, b);
			  }
			  finally
			  {
				  System.out.println();
			  }
	      }
		  static int DivideFunction(int a, int b) throws ArithmeticException
			{
		      	   return a/b;		         
			}
	       
	}
	

In the code above we used the throws Keyword at the function declaration named as DivideFunction and used ArithmeticException class. However, We can also have multiple Exception classes separated by a comma.

Output :

ArithmeticException in Java
How to use throws keyword in Java

Conclusion

We tried understnading the core concepts of exception handling in the java using the following five keywords which are crucial for handling exceptions: try, catch, throw, throws, and finally.

If you think this article was usefull to you? Share with your friends.

Scroll to Top