在
如果发生异常,它将跳转到 catch 块,然后跳转到 finally 块。
但如果没有错误,catch 块不会运行,那么 finally 块会运行吗?
C#
中,try catch finally 块如何工作?如果发生异常,它将跳转到 catch 块,然后跳转到 finally 块。
但如果没有错误,catch 块不会运行,那么 finally 块会运行吗?
C#
中,try catch finally 块如何工作?是的,无论是否存在异常,finally块都会被执行。
尝试 [ 尝试语句 ] [ 退出尝试 ] [ 捕获 [ 异常 [ As 类型 ] ] [ When 表达式 ] [ catch语句 ] [ 退出尝试 ] ] [ 捕获 ... ] [ 最终 [ finally语句 ] ] --始终运行 结束尝试
参见:http://msdn.microsoft.com/en-us/library/fk6t46tz%28v=vs.80%29.aspx
finally
,而不是在try块中使用(2)“log”调用,然后再使用catch。 - Rob Scottfinally
语句块会执行。请看我在这里的附加回答。 - Mayer Spitz如果没有异常发生,那么最终子句将被执行。以一个例子来说明。
try
{
int a = 10;
int b = 20;
int z = a + b;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
Console.WriteLine("Executed");
}
所以即使发生异常,finally语句块也会被执行。
finally
块将在方法返回之前始终执行。
尝试运行下面的代码,您会注意到finally
语句中的Console.WriteLine("executed")
在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");
}
查看结果:
Hello World!
executed
0
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");
}
catch
是否捕获到错误,finally
始终会被执行。 - Mason
try { } catch{ } finally { Trace.WriteLine("我在这里!"); }
例如 :) - Matías Fidemraizertry
块内返回会发生什么。是的,实验很好——但我通常更愿意尽可能地相信规范。 - Jon Skeet