在
C#
中,try catch finally 块如何工作?
所以如果有异常,我知道它会跳转到catch块,然后跳转到finally块。
但是如果没有错误,catch 块不会运行,但是finally 块会运行吗?
是的,无论是否有异常,finally 块都会运行。
尝试 [ 尝试语句 ] [退出尝试] [ Catch [ 异常 [ As 类型 ] ] [ When 表达式 ] [ catch 语句 ] [退出尝试]] [ 抓住 ... ] [ 最后 [finallyStatements]] --RUN ALWAYS 结束尝试
请参阅:http://msdn.microsoft.com/en-us/library/fk6t46tz%28v=vs.80%29.aspx
块将始终在方法返回之前执行。finally
尝试运行下面的代码,您会注意到
Console.WriteLine("executed")
语句中的 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; // `return` waits and executes only after the `finally` block
}
finally
{
Console.WriteLine("executed");
}
Console.WriteLine("will not be executed since the method already returned");
}
查看结果:
Hello World!
executed
0
是的,如果没有异常,finally 子句就会被执行。 举个例子
try
{
int a = 10;
int b = 20;
int z = a + b;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
Console.WriteLine("Executed");
}
所以这里如果假设发生异常,finally 也会被执行。
不管怎样,finally 块总是运行。 试试这个方法吧
public int TryCatchFinally(int a, int b)
{
try
{
int sum = a + b;
if (a > b)
{
throw new Exception();
}
else
{
int rightreturn = 2;
return rightreturn;
}
}
catch (Exception)
{
int ret = 1;
return ret;
}
finally
{
int fin = 5;
}
}
是的,Finally 总是会执行。
即使try之后没有catch块,finally块仍然会执行。
基本上,finally 可以用来释放文件流、数据库连接和图形处理程序等资源,而无需等待运行时的垃圾收集器来完成对象。
try
{
int a = 10;
int b = 0;
int x = a / b;
}
catch (Exception e)
{
Console.WriteLine(e);
}
finally
{
Console.WriteLine("Finally block is executed");
}
Console.WriteLine("Some more code here");
输出:
System.DivideByZeroException:尝试除以零。
最后块被执行
其余代码
try
{
//Function to Perform
}
catch (Exception e)
{
//You can display what error occured in Try block, with exact technical spec (DivideByZeroException)
throw;
// Displaying error through signal to Machine,
//throw is usefull , if you calling a method with try from derived class.. So the method will directly get the signal
}
finally //Optional
{
//Here You can write any code to be executed after error occured in Try block
Console.WriteLine("Completed");
}