Java

Exception Handling in Java | Explained

Java provides a concept of Exception Handling that makes it possible to handle the errors at run time, in this way, the normal follow of the program wouldn’t be affected. To handle the runtime exceptions Java provides multiple ways such as try-catch, finally, throw, throws. The normal flow can be preserved using any of these exception handling methods.

This write-up presents a profound understanding of the following aspects of Exception handling:

  • What are Exceptions in Java?
  • What is Exception Handling in Java
  • How to Handle Exceptions in Java

So, let’s get started!

What are Exceptions in Java

An unexpected event that disrupts the flow of the program is referred to as an exception and in order to make a program run successfully, we have to handle such exceptions.

What is Exception Handling in Java

It is a process of handling the errors at run-time for example IOException, ClassNotFoundException, SQLException, etc. Exception handling assists us in avoiding the disruption of the normal/regular flow of a program.

How to Handle Exceptions in Java

In Java, Exceptions can be handled in multiple ways such as, we can utilize the try-catch, throw, throws, and finally statements.

try-catch

One of the most frequently used ways of handling the exceptions is try-catch statements which are used as a pair. The code declared within the try-block will be checked for the exceptions/errors and if the exception occurs then it will be caught in the catch block.

The syntax of the try-catch statement is shown in the below snippet:

try

{

// code to be checked for exception

}

catch

{

// code to handle exceptions

}

The try block will be followed by one or more catch blocks.

Example

In this example we created, initialized a variable “num = 50” and an array of integers, next we utilized a “for loop” to iterate through each index of the array.

publicclassExceptionHandlingExample {
publicstaticvoidmain(String[] args) {
int num = 50;
int[] arr = {5, 10, 0, 25, 5};
for (inti = 0; i<arr.length; i++) {
try {
System.out.println("Result: " + num / arr[i]);
            } catch (Exception ex) {
System.out.println("An Exception occurs");
            }
        }
    }
}

Next, we write a piece of code within the try block which will be tested if an exception occurs then it will be handled in the catch block:

From the above snippet, we observe that when an error occurs, at that point the program shows a message “An Exception occurs” and afterward, the loop iterates through the remaining entries of the array i.e. the normal flow of the program didn’t disturb.

finally Statement

Another handy way of dealing with exceptions is the use of finally keyword that can be used with the try-catch statement.

It is a good practice to write the important statements/code (that you want to execute in any situation) within the finally block because it will always execute irrespective of the consequences of the try-catch block i.e. whether the exceptions are handled or not.

Example

The below code snippet will let you understand how to use the finally keyword in java:

publicclassExceptionHandlingExample {
publicstaticvoidmain(String[] args) {
try{
int number1 = 12;
int number2 = 0;
System.out.println(number1/number2);
    }
catch(ArrayIndexOutOfBoundsExceptionexcep){
System.out.println("Exception Occurred");
    }
finally
    {
System.out.println("Finally Block");
    }
}
}

Let’s have a look at the snippet below to observe how the keyword finally works:

From the above figure, we observed that the finally block executes successfully regardless of the try-catch blocks.

throw keyword

In java, exceptions can be handled explicitly with the help of throw. The throw keyword assists us in creating a customized exception, moreover, it can be used with any type of exception such as ArrayIndexOutOfBoundsException, ArithmeticException, and so on.

Example

In this example we will take a value at the time of a function call, if the input value is equal to 0, then we will throw a customized arithmetic exception.

publicclassthrowExample {
publicvoiddivide(int input) {
int number = 100;
if (input == 0) {
thrownewArithmeticException("\n You Enter 0, cannot perform division");
      } else {
System.out.println("Result: " + number / input);
       }
     }

publicstaticvoidmain(String[] args) {
throwExample obj = newthrowExample();
obj.divide(0);
  }
}

The complete code snippet along with the output is provided in the following snippet:

The above code snippet shows that passing “0” as input results in customized Exceptions which authenticates the working of the throw keyword.

Conclusion

Exception handling is a process that handles the errors/exceptions at run time. In Java, exceptions/errors can be handled with the help of try-catch, throw, and finally keywords/statements. The try-catch statements are used as a pair, while the finally can also be used with the try statement or with the try-catch statement. The try statement is used to test the code for exceptions/errors, the catch block is used to catch the exceptions the finally block always runs the code irrespective of consequences while by using the throw keyword an exception can be thrown explicitly.

About the author

Anees Asghar

I am a self-motivated IT professional having more than one year of industry experience in technical writing. I am passionate about writing on the topics related to web development.