Exception Handling
try, catch, and throw statements are used for handling exceptions, which are unexpected events or errors that can occur during the execution of a program.
trystatement: Thetryblock is used to enclose a section of code where you expect an exception might occur. The syntax for atryblock is as follows:
try {
// Code that may cause an exception
}
catchstatement: Thecatchblock is used to handle exceptions that are thrown within thetryblock. It comes after thetryblock and specifies the type of exception it can handle. The syntax for acatchblock is as follows:
catch (ExceptionType e) {
// Exception handling code
}
ExceptionTypeis the type of exception to catch. It can be a specific exception class (e.g.,ArithmeticException,IOException, or your custom exception) or a more general exception class, such asException, to catch any exception.eis a variable that holds the exception object when an exception is thrown.
throwstatement: Thethrowstatement is used to manually throw an exception. The syntax for thethrowstatement is as follows:
throw new ExceptionType("Exception message");
ExceptionTypeis the type of exception to throw."Exception message"is an optional message that provides additional information about the exception.
Example
public class ExceptionExample {
public static void main(String[] args) {
try {
int result = divide(10, 0);
} catch (ArithmeticException e) {
System.out.println("An arithmetic exception occurred: " + e.getMessage());
}
}
public static int divide(int a, int b) {
if (b == 0) {
throw new ArithmeticException("Division by zero is not allowed.");
}
return a / b;
}
}