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 / numberPrints 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” messageIf the user enters something that isn’t a number → show a friendly “enter a valid number” message
What to use
Scannerto read inputtry { ... }for code that might failcatch (...) { ... }to handle specific errors
Quick test ideas
Try running your program with:
25→ should printResult: 40→ should print your divide-by-zero messagehello→ 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 / numberPrints 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” messageIf the user enters something that isn’t a number → show a friendly “enter a valid number” message
What to use
Scannerto read inputtry { ... }for code that might failcatch (...) { ... }to handle specific errors
Quick test ideas
Try running your program with:
25→ should printResult: 40→ should print your divide-by-zero messagehello→ 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
}
}
}