Java
try/catch
Learn to catch exceptions with try/catch.
Catch errors with try/catch
An exception is an unexpected condition that disrupts the normal flow of a program. The try block wraps error-prone code; catch catches and handles the error.
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Sıfıra bölme");
}
When an exception is thrown, the try block is interrupted and the matching catch takes over. If it is not caught, the program crashes. The type in the catch parentheses determines which exception is caught. The e variable carries the exception details.
The catch parameter and type
The type in the catch parentheses determines which exceptions are caught. ArithmeticException catches only arithmetic errors; if another type comes, the catch does not engage.
catch (ArithmeticException e) {
System.out.println(e.getMessage());
}
getMessage() returns a short description of the exception. The e variable name is free; you can write ex or err. Making the type general (e.g. Exception) catches more but loses detail, so it is better to pick as specific a type as possible.
Exercise Catch division by zero
Divide int a = 10; int b = 0;. Wrap in try; catch ArithmeticException and print Sıfıra bölme.
Show example solution
try {
int result = a / b;
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("Sıfıra bölme");
}
Test yourself
-
What happens when an exception is thrown in a try block?
- The try block continues
- The program crashes immediately
- Nothing happens
- The matching catch block takes over
Show answer
The matching catch block takes over — when an exception is thrown, the try is interrupted and the catch with a matching type runs.
-
Complete the catch block
try {
int r = 10 / 0;
} ____ (ArithmeticException e) {
System.out.println("Hata");
}
Show answer
try {
int r = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Hata");
}
-
Match each exception to its scenario
- ArithmeticException
- Division by zero
- NullPointerException
- null object
- ArrayIndexOutOfBoundsException
- Out of bounds index
- NumberFormatException
- Invalid number
Next lesson: finally