| input 1: | input 2: |
|---|---|
| Enter an integer: Rats | Enter an integer: 12 |
You entered bad data. Run the program again. Good-by |
The square of 12 is 144 Good-by |
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:
try block can include:
Exception of one type or another.throw statement that explicitly throws an Exceptioncatch blocks follow the try block.
catch block.
This will be discussed later in this chapter.catch block says which type of Exception it catches.
( ExceptionType parameter )Exception object
when it is caught.Is this code fragment OK?
try
{
// various statements
}
catch (InputMismatchException ex )
{
// various statements
}
catch (IOException ex )
{
// various statements
}
System.out.println("Good-by" );