go to previous page   go to home page   go to next page        

If an NoSuchElementExeption occurs in the try{} block, what happens?

Answer:

Execution of this method stops and the method throws the NoSuchElementExeption up to its caller.

The finally{} block

If a NoSuchElementExeption occurs in this program, it immediately looses contol. The Exception is thown to the method that called it, which in this case is the Java run time system. For this program, execution will halt.

By using a finally{} block, you can ensure that some statements will always run, no matter how the try{} block was exited. Here is the try/catch/finally{} structure.

try
{
  // statements, some of which might
  // throw an exception
}

catch ( SomeExceptionType ex )
{
  // statements to handle this
  // type of exception
}


....  // more catch blocks

catch ( AnotherExceptionType ex )
{
  // statements to handle this
  // type of exception
}

finally
{
  // statements which will execute no matter
  // how the try block was exited.
}

// Statements following the structure

There can only be one finally{} block, and it must follow the catch{} blocks.

  1. If the try{} block exits normally (no exceptions occurred), then control goes directly to the finally{} block. After the finally{} block the statements following the structure get control.


  2. If the try{} block exits because of an Exception which is handled by a catch{} block, first that block executes and then control goes to the finally{} block. After the finally{} block executes, the statements following the structure get control.


  3. If the try{} block exits because of an Exception which is NOT handled by a catch{} block, control goes directly to the finally{} block. After the finally{} block executes, the Exception is thrown to the caller and control returns to the caller.

QUESTION 15:

Does the finally{}block always execute?