考虑到这一点的代码,我可以绝对肯定的是,finally块总是执行,不管something()是什么?
try {
something();
return success;
}
catch (Exception e) {
return failure;
}
finally {
System.out.println("I don't know if this will get printed out");
}
Run Code Online (Sandbox Code Playgroud) 为什么这样呢
} catch (SQLException sqle) {
sqle.printStackTrace();
} finally {
cs.close();
rs.close();
}
Run Code Online (Sandbox Code Playgroud)
而不是这个
} catch (SQLException sqle) {
sqle.printStackTrace();
}
rs.close();
cs.close();
Run Code Online (Sandbox Code Playgroud) 在try中有3个try ... catch ... finally块的排列.
执行finally块后,控制转到finally块之后的下一行.如果我删除finally块并将其所有语句移到try ... catch块之后的行中,那么它与finally块中的它们具有相同的效果吗?
我从来没有正确理解finally语句的用法.谁能告诉我两者之间的区别是什么:
try {
a;
block;
off;
statements;
} catch (Exception e) {
handle;
exception;
e;
} finally {
do;
some;
cleanup;
}
Run Code Online (Sandbox Code Playgroud)
一方面和:
try {
a;
block;
off;
statements;
} catch (Exception e) {
handle;
exception;
e;
}
do;
some;
cleanup;
Run Code Online (Sandbox Code Playgroud)
在另一
我了解“ finally”关键字在各种语言中的含义,但是,我很难理解为什么您会在口味偏爱格式之外使用它。
例如,在PHP中:
try {
possibleErrorThrownFunction();
}
catch (CustomException $customException) {
// handle custom error
}
catch (Exception $exception) {
// handle the error
}
finally {
// run this code every single time regardless of error or not
}
Run Code Online (Sandbox Code Playgroud)
这段代码在做什么和这样做之间有什么区别?
try {
possibleErrorThrownFunction();
}
catch (CustomException $customException) {
// handle custom error
}
catch (Exception $exception) {
// handle the error
}
// run this code every single time regardless of error or not
Run Code Online (Sandbox Code Playgroud)
由于捕获了错误,最后一行不是总会运行吗?在这种情况下,finally除非您只想维护代码样式的格式,否则没有实际使用的情况? …
int i=0;
try{
int j = 10/i;
}
catch(IOException e){}
finally{
Console.WriteLine("In finally");
Console.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)
在VS2008中按F5时,似乎不执行finally块.我在控制台应用程序中使用此代码.