try/catch
- Java course
- Beginner
- Lesson 106/116
- 5 min
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.
Practice Catch division by zero
Divide int a = 10; int b = 0;. Wrap in try; catch ArithmeticException and print Sıfıra bölme.
Starter code
public class Main {
public static void main(String[] args) {
int a = 10;
int b = 0;
// attempt the division, catch the error, print a message
}
}Sample solution
try {
int result = a / b;
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("Sıfıra bölme");
}Expected output
Sıfıra bölme
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 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 Correct answer
Explanation: when an exception is thrown, the try is interrupted and the catch with a matching type runs.
2 Complete the catch block
try {
int r = 10 / 0;
} ____ (ArithmeticException e) {
System.out.println("Hata");
}
try {
int r = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Hata");
}
Explanation: the catch block comes after try and catches the exception.
3 Match each exception to its scenario
| Term | Meaning |
|---|---|
ArithmeticException |
Division by zero |
NullPointerException |
null object |
ArrayIndexOutOfBoundsException |
Out of bounds index |
NumberFormatException |
Invalid number |