Java
Error handling
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.
Exercise 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.
Show example 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");
}
}
}
Test yourself
-
What does try/catch do?
- Throws errors
- Catches errors
- Throws exceptions
- Slows code down
Show answer
Catches errors — try/catch catches errors and prevents crashes.
-
Match the exception concepts
- try
- Try
- catch
- Catch
- ArithmeticException
- Math error
- Exception
- Base exception
-
Complete the catch block
try { } catch (____ e) { System.out.println("Error"); }
Show answer
try { } catch (ArithmeticException e) { System.out.println("Error"); }
Next lesson: Putting it together