Exception handling in Java

Created with Sketch.

 

Exception handling in Java

Java exception handling: we learn how to handle exceptions in Java with the help of suitable examples. Exceptions are errors that occur when a program executes. At compile time, syntax and semantics checking is done, and code doesn’t get executed on a machine, so exceptions get caught at run time.

Consider the following Java program that divides two integers.

import java.util.Scanner;

class Division {
public static void main(String[] args) {

int a, b, result;

Scanner input = new Scanner(System.in);
System.out.println(“Input two integers”);

a = input.nextInt();
b = input.nextInt();

result = a / b;

System.out.println(“Result = “ + result);
}
}

Now we compile and execute the program two times, see the output of the program in two cases:

Java program throwing Arithmetic exception (division by zero).

In the second case, we are dividing ‘a’ by zero, which isn’t allowed in the Mathematics, so a run time error occurs, i.e., an exception occurs. It happens because the input of the user isn’t valid. So we have to take preventive action, and the best thing is to notify the user that it isn’t allowed or any other meaningful message that is relevant in the context. You can see the information displayed when the exception occurred. It includes the name of the thread, file name, line of code (14 in this case) at which it occurred, name of the exception (ArithmeticException) and its description(‘/ by zero’). Exceptions not only happen because of invalid input only. There are reasons which are beyond the programmer control, such as stack overflow exception, out of memory exception (when an application requires memory larger than what is available).

Java provides a powerful way to handle such exceptions, which is known as exception handling. In it we write vulnerable code, i.e., code that can throw exception in a separate block called as try block and exception handling code in another block called the catch block. The following modified code handles the exception.

Java exception handling example

class Division {
public static void main(String[] args) {int a, b, result;

Scanner input = new Scanner(System.in);
System.out.println(“Input two integers”);

a = input.nextInt();
b = input.nextInt();

// try block

try {
result  = a / b;
System.out.println(“Result = “ + result);
}

// catch block

catch (ArithmeticException e) {
System.out.println(“Exception caught: Division by zero.”);
}
}
}

The corresponding catch block executes whenever an exception is caught. For example, the program catches ArithmeticException only. If some other kind of exception gets thrown, it doesn’t get caught, so it’s the programmer’s responsibility to take care of all exceptions. As in our try block, we are performing arithmetic, so we are capturing only arithmetic exceptions. A simple way to capture any exception is to use an object of the Exception class, as other classes inherit it. See another example below:

class Exceptions {
public static void main(String[] args) {String languages[] = { “C”, “C++”, “Java”, “Perl”, “Python” };

try {
for (int c = 1; c <= 5; c++) {
System.out.println(languages[c]);
}
}
catch (Exception e) {
System.out.println(e);
}
}
}

The output of the program:

C++
Java
Perl
Python
java.lang.ArrayIndexOutOfBoundsException: 5

Here, the catch block captures an exception because we are trying to access an array element that doesn’t exist (languages[5] in this case). Once an exception occurs, control comes out of the try block, and its remaining instructions don’t execute.

Finally block in Java

Finally block is always executed, whether an exception is thrown or not.

class Allocate {
public static void main(String[] args) {try {
long data[] = new long[1000000000];
}
catch (Exception e) {
System.out.println(e);
}

finally {
System.out.println(“Block finally always executes.”);
}
}
}

The output of the program:

Block finally always executes.
Exception in thread “main” java.lang.OutOfMemoryError: Java heap space
at Allocate.main(Allocate.java:5)

An exception occurs because we try to allocate a large amount of memory that isn’t available. This amount of memory may be available on your system; if this is the case, try increasing the amount of memory you are allocating in your program.

Leave a Reply

Your email address will not be published. Required fields are marked *