Error handling
- Java course
- Beginner
- Lesson 22/116
- 6 min
Catch invalid inputs with try/catch.
What is try/catch?
try/catch prevents the program from crashing when a piece of code throws an error. If an error occurs in the try block, the catch block runs.
try {
int result = divide(10, 0);
} catch (ArithmeticException e) {
System.out.println("Division by zero");
}Here, if divide(10, 0) throws, catch catches it and prints a message. The program continues.
This is different from the zero check: instead of preventing the error, it catches it when it happens.
What is finally?
A finally block can be added next to try/catch. finally always runs, whether or not an error occurred.
try {
// code
} catch (Exception e) {
// error
} finally {
// cleanup - always runs
}It's typically used for cleanup like closing files or terminating connections. We won't use it in the calculator yet, but it's good to know.
Practice Wrap divide call with try/catch
Wrap the divide(10, 2) call in main in a try block. Add a catch (ArithmeticException e) block that prints Division by zero with println. Keep the other calls.
Starter code
public class Main {
static int add(int a, int b) {
return a + b;
}
static int subtract(int a, int b) {
return a - b;
}
static int multiply(int a, int b) {
return a * b;
}
static int divide(int a, int b) {
if (b == 0) {
return 0;
}
return a / b;
}
public static void main(String[] args) {
System.out.println("Calculator");
System.out.println(add(5, 3));
System.out.println(subtract(5, 3));
System.out.println(multiply(5, 3));
System.out.println(divide(10, 2));
}
}Sample solution
public class Main {
static int add(int a, int b) {
return a + b;
}
static int subtract(int a, int b) {
return a - b;
}
static int multiply(int a, int b) {
return a * b;
}
static int divide(int a, int b) {
if (b == 0) {
return 0;
}
return a / b;
}
public static void main(String[] args) {
System.out.println("Calculator");
System.out.println(add(5, 3));
System.out.println(subtract(5, 3));
System.out.println(multiply(5, 3));
try {
System.out.println(divide(10, 2));
} catch (ArithmeticException e) {
System.out.println("Division by zero");
}
}
}Expected output
Calculator 8 2 15 5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does try/catch do?
- Throws errors
- Catches errors Correct answer
- Throws exceptions
- Slows code down
Explanation: try/catch catches errors and prevents crashes.
2 Match the exception concepts
| Term | Meaning |
|---|---|
try |
Try |
catch |
Catch |
ArithmeticException |
Math error |
Exception |
Base exception |
3 Complete the catch block
try { } catch (____ e) { System.out.println("Error"); }
try { } catch (ArithmeticException e) { System.out.println("Error"); }
Explanation: catch (ArithmeticException e) catches math errors.