user492052
user492052

Reputation: 151

how to handle exception if finally follows try block

If i put only finally without catch block how exception will be handled

Upvotes: 3

Views: 237

Answers (3)

Codemwnci
Codemwnci

Reputation: 54884

The exception will be passed up the call stack, as if the your try block did not exist, except the code in the finally will be executed.

Some example code

try {

   // an exception may be thrown somewhere in here

}
finally {
   // I will be executed, regardless of an exception thrown or not
}

Upvotes: 3

Stephen C
Stephen C

Reputation: 718758

If i put only finally without catch block how exception will be handled

In that situation, the exception will not caught or handled. What happens, depends on what happens in the finally clause.

  • If the statement sequence in the finally clause completes "normally", the original exception will continue propagating.
  • If the statement sequence in the finally clause completes "abruptly" for some reason then the entire try statement terminates for that reason. Abrupt terminations include throwing an exception, executing a return, break or continue. In this case, the original exception is lost without ever being "handled".

This has some rather interesting consequences. For example, the following squashes any exceptions thrown in the try block.

public void proc () {
    try {
        // Throws some exception
    } finally {
        return;
    }
}

The details of try statements with finally clauses are set out in JLS 14.20.2

Upvotes: 2

Ramp
Ramp

Reputation: 1782

Your exception will not be caught but the 'finally' block will be called and executed eventually. You can write a quick method as below and check it out :


public void testFinally(){
        try{
            throw new RuntimeException();

        }finally{
            System.out.println("Finally called!!");
        }
    }

Upvotes: 2

Related Questions