我正在为一位朋友审查一些代码,并说他在try-finally块中使用了一个return语句.即使try块的其余部分没有,Finally节中的代码是否仍会触发?
例:
public bool someMethod()
{
try
{
return true;
throw new Exception("test"); // doesn't seem to get executed
}
finally
{
//code in question
}
}
Run Code Online (Sandbox Code Playgroud) 请考虑以下代码C#代码."finally"块是否执行?
public void DoesThisExecute() {
string ext = "xlsx";
string message = string.Empty;
try {
switch (ext) {
case "xls": message = "Great choice!"; break;
case "csv": message = "Better choice!"; break;
case "exe": message = "Do not try to break me!"; break;
default:
message = "You will not win!";
return;
}
}
catch (Exception) {
// Handle an exception.
}
finally {
MessageBox.Show(message);
}
}
Run Code Online (Sandbox Code Playgroud)
哈,在我写完这篇文章之后,我意识到我本可以在Visual Studio中自己测试过.但是,请随时回答!