Handling Exceptions in User Input
This program demonstrates handling exceptions during user input.
Problem Statement
Write a Java program that handles invalid user input using try-catch.
Source Code
| 1 | import java.util.Scanner; |
| 2 | public class UserInputExceptionExample { |
| 3 | public static void main(String[] args) { |
| 4 | System.out.println("Eduinq User Input Exception Example"); |
| 5 | Scanner sc=new Scanner(System.in); |
| 6 | try { |
| 7 | System.out.print("Enter a number: "); |
| 8 | int num=sc.nextInt(); |
| 9 | System.out.println("Eduinq Number: "+num); |
| 10 | } catch(Exception e) { |
| 11 | System.out.println("Eduinq Exception: Invalid Input"); |
| 12 | } |
| 13 | } |
| 14 | } |
Program Output
Eduinq User Input Exception Example Enter a number: abc Eduinq Exception: Invalid Input
Explanation
User input may cause exceptions if type mismatch occurs. - Try-catch ensures program continues gracefully. - Improves user experience and reliability. - In enterprise systems, input validation prevents crashes and errors. Conclusion: Shows handling exceptions in user input.