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

  1. Wrap division in try block
  2. Catch ArithmeticException
  3. Print friendly error message

Related Exception Handling exercises

Practice all Exception Handling exercises · Run this idea in the Java compiler