ome*_*ega 48 c# try-catch try-catch-finally
在C#,尝试捕获最终如何阻止工作?
所以如果有异常,我知道它将跳转到catch块然后跳转到finally块.
但是,如果没有错误,catch块将不会运行,但finally块是否会运行呢?
Jam*_*ill 45
是的,无论是否存在异常,finally块都会运行.
Try
[ tryStatements ]
[ Exit Try ]
[ Catch [ exception [ As type ] ] [ When expression ]
[ catchStatements ]
[ Exit Try ] ]
[ Catch ... ]
[ Finally
[ finallyStatements ] ] --RUN ALWAYS
End Try
请参阅:http://msdn.microsoft.com/en-us/library/fk6t46tz%28v=vs.80%29.aspx
May*_*zer 14
该
finally块始终会在方法返回之前执行。
尝试运行下面的代码,您会注意到语句Console.WriteLine("executed")中的 of在有机会返回finally之前执行。RunTry()
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
Console.WriteLine(RunTry());
Console.ReadLine();
}
public static int RunTry()
{
try
{
throw new Exception();
}
catch (Exception)
{
return 0;
}
finally
{
Console.WriteLine("executed");
}
Console.WriteLine("will not be executed since the method already returned");
}
Run Code Online (Sandbox Code Playgroud)
查看结果:
Hello World!
executed
0
Run Code Online (Sandbox Code Playgroud)
Soh*_*ail 12
是的,如果没有异常,则finally子句会被执行.举个例子
try
{
int a = 10;
int b = 20;
int z = a + b;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
Console.WriteLine("Executed");
}
Run Code Online (Sandbox Code Playgroud)
所以这里如果假设发生异常也会终止执行.