在C#
中,try catch finally 块如何工作?
所以如果出现异常,我知道它会跳转到catch块,然后跳转到finally块。
但是如果没有错误,catch 块不会运行,但是 finally 块会运行吗?
在C#
中,try catch finally 块如何工作?
所以如果出现异常,我知道它会跳转到catch块,然后跳转到finally块。
但是如果没有错误,catch 块不会运行,但是 finally 块会运行吗?
是的,不管有没有异常,finally 块都会运行。
尝试 [尝试语句] [退出尝试] [捕捉[异常[作为类型]][当表达式] [捕捉语句] [退出尝试]] [ 抓住 ... ] [ 最后 [ finallyStatements ] ] --始终运行 结束尝试
请参阅:http: //msdn.microsoft.com/en-us/library/fk6t46tz%28v=vs.80%29.aspx
是的,如果没有例外,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
块将始终在方法返回之前执行。
尝试运行下面的代码,您会注意到语句中的Console.WriteLine("executed")
of 在有机会执行之前执行的位置。finally
Console.WriteLine(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
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;
}
}
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");
}
是的,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:试图除以零。
finally 块被执行
其余代码