Added example of an inputmismatchexception (#28773)
Added example of an inputmismatchexception for inputting an integer using the scanner.
This commit is contained in:
committed by
Christopher McCormack
parent
badf7bb094
commit
b44d80dd9a
@ -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)
|
||||
|
||||
|
Reference in New Issue
Block a user