在C#
中,try如何捕获最终阻止工作?
因此,如果有异常,我知道它将跳转到catch块然后跳转到finally块。
但是如果没有错误,catch块就不会运行,但是finally块是否会运行呢?
答案 0 :(得分:44)
是的,无论是否存在异常,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
答案 1 :(得分:13)
是的,如果没有异常,则finally子句会被执行。 举个例子
try
{
int a = 10;
int b = 20;
int z = a + b;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
Console.WriteLine("Executed");
}
所以这里如果假设发生异常也会终止执行。
答案 2 :(得分:5)
catch的常见用法最后是在try块中获取和使用资源,处理catch块中的异常情况,并释放finally块中的资源。
有关重新抛出异常的更多信息和示例,请参阅try-catch和Throwing Exceptions。有关finally块的更多信息,请参阅try-finally。
public class EHClass
{
void ReadFile(int index)
{
// To run this code, substitute a valid path from your local machine
string path = @"c:\users\public\test.txt";
System.IO.StreamReader file = new System.IO.StreamReader(path);
char[] buffer = new char[10];
try
{
file.ReadBlock(buffer, index, buffer.Length);
}
catch (System.IO.IOException e)
{
Console.WriteLine("Error reading from {0}. Message = {1}", path, e.Message);
}
finally
{
if (file != null)
{
file.Close();
}
}
// Do something with buffer...
}
}
答案 3 :(得分: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;
}
}
答案 4 :(得分:0)
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");
}
答案 5 :(得分:0)
是的,最终将始终执行。
即使尝试后没有catch块,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:尝试除以零。
最后一个块被执行
其余代码
来源:Exception handling in C# (With try-catch-finally block details)
答案 6 :(得分:0)
finally
块将始终在方法返回之前执行。
尝试运行以下代码,您会注意到Console.WriteLine("executed")
语句中的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");
}
查看结果: