Bird
0
0

You want to read an integer from user input safely. Which code correctly uses try-catch to handle invalid input?

hard📝 Application Q15 of 15
Java - Exception Handling
You want to read an integer from user input safely. Which code correctly uses try-catch to handle invalid input?
import java.util.Scanner;

Scanner sc = new Scanner(System.in);
int num;
try {
  num = sc.nextInt();
  System.out.println("You entered: " + num);
} catch (Exception e) {
  System.out.println("Invalid input");
}
AMissing finally block causes error
BShould catch IOException instead of Exception
CCorrectly handles invalid input with try-catch
DTry block should be outside Scanner usage
Step-by-Step Solution
Solution:
  1. Step 1: Understand input reading

    Using sc.nextInt() reads integer input; invalid input throws InputMismatchException, a subclass of Exception.
  2. Step 2: Check try-catch usage

    The try block attempts input; catch block handles any Exception, printing "Invalid input" if input is wrong.
  3. Final Answer:

    Correctly handles invalid input with try-catch -> Option C
  4. Quick Check:

    Try-catch handles input errors = B [OK]
Quick Trick: Catch Exception to handle all input errors safely [OK]
Common Mistakes:
  • Thinking finally is mandatory
  • Catching wrong exception type
  • Placing try block incorrectly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes