3

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

user492052
  • 151
  • 1
  • 2
  • Related question here http://stackoverflow.com/questions/3954656/loss-exception-in-block-catch/3954759#3954759 with JLS citations. – andersoj Oct 30 '10 at 12:04

3 Answers3

3

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
}
Codemwnci
  • 54,176
  • 10
  • 96
  • 129
  • According to the example from the Java Language Specification referenced in Stephen C's answer, the finally block will be executed regardless, it will be executed **before** anything further up the stack catches it, and if the finally block exits abnormally (e.g. with `return`), the exception will not propagate up the stack. – David Gelhar Oct 30 '10 at 14:23
2

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!!");
        }
    }

Ramp
  • 1,772
  • 18
  • 24
2

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

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • This seems to be the only correct answer. It's certainly the only one that gives a reference backing up its claims. – David Gelhar Oct 30 '10 at 14:18