In: Computer Science
Exercise 1:
You are required to re-write the following code to catch the exception that can occur.
import java.util.Scanner;
public class ExceptionDemo
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an integer: ");
int number = scanner.nextInt();
// Display the result
System.out.println( "The number entered is " + number);
}
}
import java.util.InputMismatchException;
import java.util.Scanner;
public class ExceptionDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Enter an integer: "); //try block to find exception
int number = scanner.nextInt();
System.out.println("The number entered is " + number);
} catch (InputMismatchException e) { //catch block to catch exception
e.printStackTrace();
}
}
}
Output:-
Note:- Please comment
if you face any problem. :)