Java Exception Handling
Exception handling in Java: try-catch, throw, throws, custom exceptions, and best practices.
Try-Catch
// Basic try-catch
try {
int result = 10 / 0; # may throw exception
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}
Multiple Catch
// Multiple catch blocks
try {
int[] arr = new int[5];
arr[10] = 50; # out of bounds
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Index out of bounds"); # specific
} catch (Exception e) {
System.out.println("General error"); # catch all
}
Finally Block
// Always executes
try {
int result = 10 / 2;
} catch (Exception e) {
System.out.println("Error");
} finally {
System.out.println("Cleanup code"); # always runs
}
Throw Exception
// Throw exception manually
public void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Too young"); # force exception
}
}
Throws Keyword
// Declare exception in method
public void readFile() throws IOException { # method may throw
FileReader file = new FileReader("file.txt");
BufferedReader br = new BufferedReader(file);
br.close();
}
Custom Exception
// Create custom exception
public class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message); # pass to parent
}
}
// Use custom exception
throw new InvalidAgeException("Age must be 18+");
Try-With-Resources
// Auto-close resources
try (FileReader fr = new FileReader("file.txt")) { # auto-close
int c = fr.read();
} catch (IOException e) {
e.printStackTrace();
}
Common Exceptions
// Checked exceptions (must handle)
IOException # file operations
FileNotFoundException # file not found
SQLException # database errors
// Unchecked exceptions (runtime)
NullPointerException # null reference
ArrayIndexOutOfBoundsException # array index
ArithmeticException # math errors
NumberFormatException # invalid conversion