Home › Java Tutorial › Java exceptions
Java exceptions
Handle errors without crashing.
Put risky code in try and handle the problem in catch. finally always runs. Use throw to raise your own error. Checked exceptions (like IOException) must be caught or declared with throws.
Example code
public class Main {
public static void main(String[] args) {
try {
int d = 0;
int x = 10 / d;
System.out.println(x);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
} finally {
System.out.println("Done");
}
try {
Integer.parseInt("abc");
} catch (NumberFormatException e) {
System.out.println("Not a number");
}
}
}