Control Structures
6. Exception Handling (try-catch)
Exception handling controls the flow when errors (exceptions) occur, preventing program crashes.
Syntax:
java
try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Handle the exception
} finally {
// Optional: Code that always executes
}
Example:
public class TryCatchExample {
public static void main(String[] args) {
try {
int[] arr = {1, 2, 3};
System.out.println(arr[5]); // Throws ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Invalid index"); // Output: Error: Invalid index
} finally {
System.out.println("This always executes");
}
}
}
Notes:
try: Contains code that might throw an exception.
catch: Handles specific exceptions.
finally: Executes regardless of whether an exception occurs (optional).
Multiple catch blocks can handle different exception types.
throw: Manually throws an exception (e.g., throw new Exception("Error");).
throws: Declares exceptions a method might throw (e.g., public void method() throws IOException).