Solution: Try-Catch

This solution reads a number from the user and divides 100 by it. The key idea is: “Try the risky code, and catch errors instead of crashing.”

What the code is doing

  • Scanner input = new Scanner(System.in);
    Creates a tool to read what the user types.

  • try { ... }
    Wraps the lines that might fail:

    • Reading an integer with nextInt()

    • Dividing 100 / number

  • catch (ArithmeticException e)
    Runs if the user typed 0, because dividing by zero is not allowed.

  • catch (InputMismatchException e)
    Runs if the user typed something that isn’t an integer (like "hi").

  • input.close();
    Closes the scanner (good cleanup habit).

Why there are two catches

Different problems need different messages:

  • Divide by zero → math error (ArithmeticException)

  • Not a number → input error (InputMismatchException)

That’s it: same program, but now it’s safe and user-friendly.

Solution: Try-Catch

This solution reads a number from the user and divides 100 by it. The key idea is: “Try the risky code, and catch errors instead of crashing.”

What the code is doing

  • Scanner input = new Scanner(System.in);
    Creates a tool to read what the user types.

  • try { ... }
    Wraps the lines that might fail:

    • Reading an integer with nextInt()

    • Dividing 100 / number

  • catch (ArithmeticException e)
    Runs if the user typed 0, because dividing by zero is not allowed.

  • catch (InputMismatchException e)
    Runs if the user typed something that isn’t an integer (like "hi").

  • input.close();
    Closes the scanner (good cleanup habit).

Why there are two catches

Different problems need different messages:

  • Divide by zero → math error (ArithmeticException)

  • Not a number → input error (InputMismatchException)

That’s it: same program, but now it’s safe and user-friendly.