From b44d80dd9ad6a27052940fb044103b9314e01ea4 Mon Sep 17 00:00:00 2001 From: jamiesteck Date: Sat, 12 Jan 2019 09:08:45 -0800 Subject: [PATCH] Added example of an inputmismatchexception (#28773) Added example of an inputmismatchexception for inputting an integer using the scanner. --- .../english/java/exception-handling/index.md | 21 ++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/guide/english/java/exception-handling/index.md b/guide/english/java/exception-handling/index.md index 765ceb5865..d939889ac6 100644 --- a/guide/english/java/exception-handling/index.md +++ b/guide/english/java/exception-handling/index.md @@ -63,6 +63,25 @@ finally { } ``` +### Example +Here is a practical example. Suppose you are using a Scanner object to input an integer. If the user enters a decimal instead of an integer, an error would normally occur, causing the program to end. However, if you add an exception clause as shown below, the error can be caught and allow your program to continue running. + +``` +Scanner input = new Scanner(System.in); +try +{ + System.out.print("Enter an integer: "); + int num1 = input.nextInt(); + System.out.printf("You entered the number %d%n", num1); +} +catch(InputMismatchException e) +{ + System.out.println("Must enter a valid integer."); + input.nextLine(); //clear the input line of previous input +} +``` +If an integer is entered, the "try" code block will execute successfully. If something other than an integer is entered, the "catch" code block will execute. + ## How to use throws clause ```java @@ -71,6 +90,7 @@ public methodName throws ExceptionType1, ExceptionType2 { } ``` + However, it is not recommended to throw exceptions without being handled. ## Advantage of Exception Handling @@ -80,4 +100,3 @@ Tip: If you are not really sure of what kind of exceptions your application may #### More Information: - [Oracle Java Docs : Exception](https://docs.oracle.com/javase/specs/jls/se7/html/jls-11.html) -