What is an exception?
When something goes wrong while a program runs – dividing by zero, reading a number that isn't a number – Java throws an exception. If nobody catches it, the program crashes:
public class Main {
public static void main(String[] args) {
int a = 10;
int b = 0;
System.out.println(a / b);
System.out.println("This never prints");
}
}Output (Java stops with an error)
Exception in thread "main" java.lang.ArithmeticException: / by zero
Catching it
Put the risky code in a try block. If an exception happens, Java jumps to the catch block instead of crashing:
public class Main {
public static void main(String[] args) {
try {
int result = 10 / 0;
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("Oops: " + e.getMessage());
}
System.out.println("The program keeps going");
}
}Output
Oops: / by zero The program keeps going
Think of it like this: A trapeze artist with a safety net.
tryis the risky jump;catchis the net. If they fall, the show goes on.
Checking user input
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String text = sc.nextLine();
try {
int age = Integer.parseInt(text);
System.out.println("Next year you'll be " + (age + 1));
} catch (NumberFormatException e) {
System.out.println("'" + text + "' is not a number");
}
}
}Input (what the user types)
twenty
Output
'twenty' is not a number
Common exceptions
| Exception | Happens when... |
|---|---|
ArithmeticException | dividing a whole number by zero |
NumberFormatException | turning bad text into a number |
ArrayIndexOutOfBoundsException | using an array index that doesn't exist |
NullPointerException | using a variable that holds null |
InputMismatchException | sc.nextInt() gets something that isn't a number |