Exceptions
An exception stops normal flow when something goes wrong. try runs risky code, catch handles a specific exception type and finally always runs. throw raises your own exception. Checked exceptions must be handled or declared with throws.
Example
public class Main {
static int divide(int a, int b) {
if (b == 0) throw new IllegalArgumentException("Cannot divide by zero");
return a / b;
}
public static void main(String[] args) {
try {
System.out.println(divide(10, 2));
System.out.println(divide(1, 0));
} catch (IllegalArgumentException e) {
System.out.println("Caught: " + e.getMessage());
} finally {
System.out.println("Done");
}
try {
int[] a = new int[2];
a[5] = 1;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Bad index");
}
}
}Result
5 Caught: Cannot divide by zero Done Bad index
Exercise
Handle the error.
try { risky(); } (Exception e) {}
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.