Basic Try-Catch in Java: Explanation & Practice
Handle a simple exception
Problem summary
Handle division by zero exception and print an error message.
Starter code
public class Main {
public static void main(String[] args) {
int a = 10;
int b = 0;
// Try to divide a by b
// Catch ArithmeticException
// Print: Error: Cannot divide by zero
}
}Expected output and test cases
- Handle division by zero
Error: Cannot divide by zero
Hints
- Wrap division in try block
- Catch ArithmeticException
- Print friendly error message
Related Exception Handling exercises
- Practice Multiple Catch Blocks in Java
- Practice Using Finally Block in Java
- Practice Throwing Exceptions in Java
Practice all Exception Handling exercises · Run this idea in the Java compiler