Challenge: Try-Catch

You’re going to ask the user for a number, then divide 100 by it.

Why this matters: user input can cause your program to crash (like dividing by zero or typing letters). In this challenge, you’ll use try/catch to handle those cases safely.

Your task

Write a Java program that:

  • Prompts the user to enter a number

  • Tries to compute 100 / number

  • Prints the result if it works

  • Does not crash if something goes wrong

Must handle these cases

  • If the user enters 0 → show a friendly “can’t divide by zero” message

  • If the user enters something that isn’t a number → show a friendly “enter a valid number” message

What to use

  • Scanner to read input

  • try { ... } for code that might fail

  • catch (...) { ... } to handle specific errors

Quick test ideas

Try running your program with:

  • 25 → should print Result: 4

  • 0 → should print your divide-by-zero message

  • hello → should print your invalid-input message

Challenge: Try-Catch

You’re going to ask the user for a number, then divide 100 by it.

Why this matters: user input can cause your program to crash (like dividing by zero or typing letters). In this challenge, you’ll use try/catch to handle those cases safely.

Your task

Write a Java program that:

  • Prompts the user to enter a number

  • Tries to compute 100 / number

  • Prints the result if it works

  • Does not crash if something goes wrong

Must handle these cases

  • If the user enters 0 → show a friendly “can’t divide by zero” message

  • If the user enters something that isn’t a number → show a friendly “enter a valid number” message

What to use

  • Scanner to read input

  • try { ... } for code that might fail

  • catch (...) { ... } to handle specific errors

Quick test ideas

Try running your program with:

  • 25 → should print Result: 4

  • 0 → should print your divide-by-zero message

  • hello → should print your invalid-input message

public class Main {
    public static void main(String[] args) {
        try {
            int result = 10 / 0;
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Oops! You can not divide by zero.");
            
            // Update the given code with yours
        }
    }
}
Project: try-catch