Java

Try, Catch, Throw, and Finally statements in Java | Explained

In any programming language including Java, there is always a possibility that an error occurs at the time of code execution, as a result, the program stops working and throws an error. In programmatically terms this phenomenon is referred to as Exceptions. Java provides the solution that can handle such run-time exceptions/errors known as exception handling.

In Java multiple ways can be adopted to handle the exceptions, in this write-up we will discuss the following ways of exception handling:

All the above-mentioned approaches will be discussed in this write-up with the help of some examples. However, before heading towards these approaches first we need to understand why it is necessary to handle exceptions in java.

Why Exception Handling in Java

In case we face any error, normally the program stops its execution however the exception handling ensures that the normal flow of the program shouldn’t break.

Let’s consider a scenario for the profound understanding of exception handling in java:

Suppose we have five statements in a program and the exception occurs at the third statement then a normal program stops its execution at that point, and the remaining two statements wouldn’t execute. However, if we apply exception handling then the normal flow wouldn’t be affected i.e. exception will be shown for the affected statement only and all other statements will execute successfully.

Example

Let’s consider the below example which didn’t consider the exception handling mechanism. Now, what will happen if an error occurs?

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

In this program, we have an array of integers, within the loop, we specify a condition arr.length which represents iterate until the last entry of the array. And within the body of the loop, we have a number “50” and it will be divided by each value of the array:

From the output, it is clear that the program terminates when an error occurs and it doesn’t print the remaining values of the array.

Therefore, to deal with such scenarios, the java programmers utilize the concept of exception handling so that if an error occurs then instead of terminating the whole program it should throw the exception for the affected statement only.

Exception handling using try-catch

One of the simplest and easiest ways to deal with exceptions is try-catch statements that come up as a pair. The code specified within the try block will be tested for the exceptions/errors and if an exception occurs then it will be caught in the catch block.

The basic syntax of the try-catch statement will look like this:

try

{

// code to be tested for exception

}

catch

{

// code to handle exceptions

}

The try block will always be followed by at least one catch block.

Example

Let’s extend the previous example a little bit more and add the try-catch statements to deal with the exceptions.

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");
            }
        }
    }
}

The complete code alongside its respective output is shown in the following snippet:

This time 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.

Exception handling using finally Statement

In java, the finally keyword can be used with try-catch and it will always execute irrespective of whether the exceptions are handled or not.

Note: Always write the important statements/code (that you want to execute in any situation) within the finally block.

Example

The below code snippet shows how finally block works 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");
    }
}
}

The complete code and its respective output are shown in the following screenshot:

As in the above code, we utilize the ArrayOutOfBound exception, therefore, it is unable to handle an Arithmetic exception. However, from the above snippet, it is clear that the finally block executes regardless of the consequences (i.e. exception handled or not).

Exception handling using throw keyword

The throw keyword can be used to throw an exception explicitly (i.e. it allows us to create a customized exception). It can be used with any exception type such as ArrayIndexOutOfBoundsException, ArithmeticException, and so on.

Example

In this example we will take a value at the time of 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

Java provides multiple statements to handle run-time exceptions/errors such as try, catch, finally, throw. try-catch statements come up as a pair, the try block tests the code for exceptions/errors if an exception occurs then it will be caught in the catch block. The finally keyword can be used with try-catch and it will always execute irrespective of whether the exceptions are handled or not while the throw keyword is used to throw an exception explicitly. This write-up provides a detailed understanding of how to deal with exceptions in java.

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.