当前位置: 技术问答>java相关
执行顺序
来源: 互联网 发布时间:2015-07-27
本文导语: 如下代码: public synchronized int executeUpdate(String usrId,String query, String dbname) throws SQLException { int rowaffected = 0; Connection con = null; con =getConnection(dbname,true) ; if(con !=null){ Statement ...
如下代码:
public synchronized int executeUpdate(String usrId,String query, String dbname) throws SQLException
{
int rowaffected = 0;
Connection con = null;
con =getConnection(dbname,true) ;
if(con !=null){
Statement stmt = con.createStatement();
rowaffected = stmt.executeUpdate(query);
stmt.close();
stmt = null;
}
try{
commit(con);
}catch(SQLException commitEx){
rowaffected = 0;
rollback(con);
throw commitEx;
}finally{
if(con !=null)
close(con);
}
return rowaffected;
}
我想问当产生违例时.是否执行finally块中的代码?throw 是否像return一样结束
此方法.
public synchronized int executeUpdate(String usrId,String query, String dbname) throws SQLException
{
int rowaffected = 0;
Connection con = null;
con =getConnection(dbname,true) ;
if(con !=null){
Statement stmt = con.createStatement();
rowaffected = stmt.executeUpdate(query);
stmt.close();
stmt = null;
}
try{
commit(con);
}catch(SQLException commitEx){
rowaffected = 0;
rollback(con);
throw commitEx;
}finally{
if(con !=null)
close(con);
}
return rowaffected;
}
我想问当产生违例时.是否执行finally块中的代码?throw 是否像return一样结束
此方法.
|
任何时候finally块中的语句都会被执行,请看如下测试程序:
import java.io.*;
class Test{
public static void main(String[] args)
throws FileNotFoundException, IOException{
try{
BufferedReader in=new BufferedReader(new FileReader("xxx.exe"));
in.close();
}catch(FileNotFoundException e){
throw e;
}catch(IOException e){
throw e;
}finally{
System.out.println("error");//用于验证
}
}
}
执行结果:
error //证明finally语句块被执行
Exception in thread "main" java.io.FileNotFoundException: ok.exe (系统找不到指定
的文件。)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.(FileInputStream.java:64)
at java.io.FileReader.(FileReader.java:38)
at Test.main(Test.java:7)
import java.io.*;
class Test{
public static void main(String[] args)
throws FileNotFoundException, IOException{
try{
BufferedReader in=new BufferedReader(new FileReader("xxx.exe"));
in.close();
}catch(FileNotFoundException e){
throw e;
}catch(IOException e){
throw e;
}finally{
System.out.println("error");//用于验证
}
}
}
执行结果:
error //证明finally语句块被执行
Exception in thread "main" java.io.FileNotFoundException: ok.exe (系统找不到指定
的文件。)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.(FileInputStream.java:64)
at java.io.FileReader.(FileReader.java:38)
at Test.main(Test.java:7)
|
是的,所以如果产生违例,finally中的代码就不会被执行了。throw 以后代码就结束了。
|
finally块代码会执行
即使return也不能结束
--- ZJQ
即使return也不能结束
--- ZJQ