Answer:
| input 1: | input 2: |
|---|---|
| Enter an integer: Rats | Enter an integer: 12 |
|
|
Syntax of try{} and catch{}
Here is ONE form of the try/catch structure.
(There are other forms soon to be discussed.)
try
{
// statements which might throw
// various types of exceptions
}
catch ( SomeExceptionType ex )
{
// statements to handle this
// type of exception
}
catch ( AnotherExceptionType ex )
{
// statements to handle this
// type of exception
}
catch ( YetAnotherExceptionType ex )
{
// statements to handle this
// type of exception
}
// Statements following the structure
Here are a few syntax rules:
- The statements in the
try{}block can include:- Statements that always work.
- Statements that might throw an
Exceptionof one type or another.
- One or several
catch{}blocks follow thetry()block.- Sometimes there can be no
catch{}blocks. This will be discussed later in this chapter.
- Sometimes there can be no
- Each
catch{}block describes the type ofExceptionit catches. - It does this in a one-item parameter list:
( ExceptionType parameter ) - the parameter is a reference variable that will refer to the
Exceptionobject when it is caught.
QUESTION 6:
Is the following code fragment OK?
try
{
// various statements
}
catch (InputMismatchException ex )
{
// various statements
}
catch (IOException ex )
{
// various statements
}
System.out.println("Good-by" );