简体   繁体   中英

How we make Java Code to jump to finally

Here's the piece of code I am seeing

 1 session s=null; 
 2 try{
 3    s= SessionCreator.createSession();
 4    System.out.println("Session Created");
 5    s.validate(); 
 6 }catch (Exception e){
 7    e.printStackTrace(); 
 8 }finally{
 9    s.close();
10 }

Debugger jumps from line 3 to line 9, How is this possible ? Neither 4,5 nor 7 was executed. This puzzles me. line 3 is a vendor code, So I don't know what is happening. Any clues ?

Try using catch (Throwable e) instead of Exception . An Error might be thrown and an error is not subclass of "Exception" but extends "Throwable".

Here is an example: http://ideone.com/Zs7HGw

Read up here.

http://docs.oracle.com/javase/tutorial/essential/exceptions/handling.html

Any code put in the try block has the potential to fail. If it does fail (probably on line 2 or 4), it should break out of the try block and into the catch block. The finally block will be executed either way.

Your description sounds correct if line 2 is failing, except that line 6 should be getting executed. If line 6 is not getting executed, then your entire try block is succeeding. What is the exact output?

如果第4行和第7行都没有执行, 也许 (并且我强调“也许”是因为我不十分了解Java异常机制),第3行不是抛出Exception对象,而是抛出ErrorThrowable

I know this problem only from remote debugging sessions where the underlying code server side does not correspond with the code we see locally. As the debugger only communicates the lines and not the code itself, it can lead to impossible jumps.

Do you debug remotely? Even if not, can you build the whole project again?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM