I am trying to put a while loop inside a try /catch block. To my curiosity finally of that try catch is not executed when the while loop exits. Can some explain what is happening actually? I tried to google, but cnould not find any details.
Asked
Active
Viewed 2,802 times
-1
-
6Please show some code. – JohnB Sep 01 '12 at 07:40
-
According to the JLS what you describe cannot happen. Please show us the code that demonstrates this behaviour. (My guess is that you are misinterpreting something ...) – Stephen C Sep 01 '12 at 07:59
-
@StephenC yes it can, see my answer. – Nir Alfasi Sep 01 '12 at 08:40
-
Yea ... well apart from that, or crashing the JVM. (And I'm sure that is not what the OP is actually talking about!) – Stephen C Sep 01 '12 at 10:12
2 Answers
5
I assume your code looks like this:
try
{
while (...)
{
// ...
}
}
catch (FooException ex)
{
// This only executes if a FooException is thrown.
}
finally
{
// This executes whether or not there is an exception.
}
The catch block is only executed if there is an exception. The finally block usually executes whether or not an exception was thrown. So you will probably find that your finally block is actually being executed. You can prove this to yourself by placing a line there that causes some output to the console.
However there are situations in which the finally block doesn't run. See here for more details:

Community
- 1
- 1

Mark Byers
- 811,555
- 193
- 1,581
- 1,452
-
4
-
@cheeken: OK, yeah I see what you mean. Question is hard to understand. He should post his code. – Mark Byers Sep 01 '12 at 08:00
-
This is what i have given as statement. What will happen after the while loop finished its execution? – Tinkerbel Sep 01 '12 at 08:25
-
1
1
It can happen only if your program exits either by using System.exit()
or if an Error
or Throwable
were thrown (vs. Exception
that will be caught).
Try the following:
public static void main(String[] args) {
try{
System.out.println("START!");
int i=0;
while(true){
i++;
if(i > 10){
System.exit(1);
}
}
}
catch (Exception e) {
// TODO: handle exception
}
finally{
System.out.println("this will not be printed!");
}
}

Nir Alfasi
- 53,191
- 11
- 86
- 129