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.
try
statement: Thetry
block is used to enclose a section of code where you expect an exception might occur. The syntax for atry
block is as follows:
try {
// Code that may cause an exception
}
catch
statement: Thecatch
block is used to handle exceptions that are thrown within thetry
block. It comes after thetry
block and specifies the type of exception it can handle. The syntax for acatch
block is as follows:
catch (ExceptionType e) {
// Exception handling code
}
ExceptionType
is 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.e
is a variable that holds the exception object when an exception is thrown.
throw
statement: Thethrow
statement is used to manually throw an exception. The syntax for thethrow
statement is as follows:
throw new ExceptionType("Exception message");
ExceptionType
is 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;
}
}