Exceptions are errors that occur during program execution, such as a file that cannot be found or a division by zero. It is a mechanism that allows developers to gracefully manage runtime errors and prevent their programs from crashing.
This guide will illustrate the try-catch block along with practical implementation in Java.
How to Use Try-catch Block in Java?
In Java, the try-catch block offers any program to recover gracefully from exceptions by handling them in a controlled manner. The syntax in Java is as follows:
// script
} catch (ExceptionType e) {
// script
}
Here, the script that might throw an exception is placed inside the “try” block. If this exception occurs during the execution of this code, Java jumps to the “catch” block and executes the script that is present in it.
The “ExceptionType” refers to the type of exception. This can be any subclass of the Throwable class, such as IOException, NullPointerException, or ArithmeticException.
Example
Let us focus on a script to divide two numbers from user input. If the user provides an invalid input or if the second number is zero, we want to handle these exceptions gracefully.
public class DivideByZero {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
try {
System.out.print("Enter the first number: ");
int num1 = input.nextInt();
System.out.print("Enter the second number: ");
int num2 = input.nextInt();
int result = num1 / num2;
System.out.println("The result is: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
System.out.println("Cannot divide by zero!");
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
System.out.println("Invalid input!");
}
input.close();
}
}
In this code, if the exception occurs during the execution of this code, Java jumps to the proper catch block and executes the code present in it. Otherwise, the result can be seen below:
Output
The output computes both inputs and returns the result which is “5”.
ArithmeticException is Thrown
If an ArithmeticException is thrown (i.e., the user attempted to divide by zero), the first catch block executes as below:
The error message “Cannot divide by zero!” is displayed.
Any Other Type of Exception is Thrown
If any other type of exception is thrown (i.e., the user provided invalid input), the second catch block executes:
The error message “Invalid input!” has been displayed by taking the wrong input.
Conclusion
In Java, a try-catch block is a programming construct utilized to handle/manage exceptions. By using try-catch blocks, users can write more robust and fault-tolerant programs that are less likely to crash or produce unexpected results in the face of errors or unexpected conditions. In either case, the program will not crash, and the user presents with a user-friendly error message. This guide has explained all examples for the usage of the try-catch block in Java.