Category | Description | Examples |
---|---|---|
Checked | Must be handled with try-catch |
IOException , SQLException |
Unchecked | Occur at runtime, optional to handle | NullPointerException , ArithmeticException |
Errors | Serious problems, usually not handled | OutOfMemoryError , StackOverflowError |
1
2
3
4
5
try {
// Code that may throw an exception
} catch (ExceptionType name) {
// Code to handle the exception
}
1
2
3
4
5
6
7
8
9
10
public class TryCatchExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // This causes ArithmeticException
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero.");
}
}
}
1
Error: Cannot divide by zero.
You can catch different types of exceptions separately:
1
2
3
4
5
6
7
8
try {
int[] arr = {1, 2, 3};
System.out.println(arr[5]); // ArrayIndexOutOfBoundsException
} catch (ArithmeticException e) {
System.out.println("Math error.");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Invalid array index.");
}
Note: Catch blocks are priorities from top to bottom
The finally block is always executed, even if an exception occurs or not. Great for cleanup code (e.g., closing files or scanners).
1
2
3
4
5
6
7
8
9
10
11
Scanner sc = new Scanner(System.in);
try {
System.out.println("Enter a number: ");
int n = sc.nextInt();
System.out.println("Number: " + n);
} catch (Exception e) {
System.out.println("Invalid input.");
} finally {
sc.close(); // Always runs
System.out.println("Scanner closed.");
}
Use throw to manually raise an exception.
1
throw new IllegalArgumentException("Negative age not allowed");
Used to declare that a method may throw exceptions.
1
2
3
public void readFile() throws IOException {
// read file here
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class ExceptionDemo {
public static int divide(int a, int b) throws ArithmeticException {
if (b == 0) {
throw new ArithmeticException("Cannot divide by zero.");
}
return a / b;
}
public static void main(String[] args) {
try {
int result = divide(10, 0);
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Caught an error: " + e.getMessage());
} finally {
System.out.println("Division attempt complete.");
}
}
}
Output:
1
2
Caught an error: Cannot divide by zero.
Division attempt complete.