我见过有人说,使用不带参数的catch是一种糟糕的形式,尤其是当catch什么都不做的时候:

StreamReader reader=new  StreamReader("myfile.txt");
try
{
  int i = 5 / 0;
}
catch   // No args, so it will catch any exception
{}
reader.Close();

然而,这被认为是良好的形式:

StreamReader reader=new  StreamReader("myfile.txt");
try
{
  int i = 5 / 0;
}
finally   // Will execute despite any exception
{
  reader.Close();
}

据我所知,将清理代码放在finally块和将清理代码放在try. catch块之后的唯一区别是,如果你在try块中有返回语句(在这种情况下,finally中的清理代码将运行,但try. catch块之后的代码将不会运行)。

否则,最后有什么特别的?


当前回答

使用finally,您可以清理资源,即使您的catch语句将异常抛出给调用程序。与包含空catch语句的示例相比,差别不大。但是,如果在catch中执行了一些处理并抛出错误,或者甚至根本没有catch, finally仍然会运行。

其他回答

摄自:这里

引发和捕获异常不应该作为方法成功执行的一部分常规发生。在开发类库时,必须让客户端代码有机会在执行可能引发异常的操作之前测试错误条件。例如,System.IO.FileStream提供了一个CanRead属性,可以在调用Read方法之前进行检查,以防止引发潜在的异常,如下所示的代码片段:

Dim str As Stream = GetStream() If (str.CanRead) Then '代码来读取流 如果

The decision of whether to check the state of an object prior to invoking a particular method that may raise an exception depends on the expected state of the object. If a FileStream object is created using a file path that should exist and a constructor that should return a file in read mode, checking the CanRead property is not necessary; the inability to read the FileStream would be a violation of the expected behavior of the method calls made, and an exception should be raised. In contrast, if a method is documented as returning a FileStream reference that may or may not be readable, checking the CanRead property before attempting to read data is advisable.

To illustrate the performance impact that using a "run until exception" coding technique can cause, the performance of a cast, which throws an InvalidCastException if the cast fails, is compared to the C# as operator, which returns nulls if a cast fails. The performance of the two techniques is identical for the case where the cast is valid (see Test 8.05), but for the case where the cast is invalid, and using a cast causes an exception, using a cast is 600 times slower than using the as operator (see Test 8.06). The high-performance impact of the exception-throwing technique includes the cost of allocating, throwing, and catching the exception and the cost of subsequent garbage collection of the exception object, which means the instantaneous impact of throwing an exception is not this high. As more exceptions are thrown, frequent garbage collection becomes an issue, so the overall impact of the frequent use of an exception- throwing coding technique will be similar to Test 8.05.

Try{…}catch{}并不总是坏的。这不是一种常见的模式,但当我无论如何都需要关闭资源时,我倾向于使用它,比如在线程末尾关闭(可能)打开的套接字。

最后无论如何都会执行。如果你的try块成功,它就会执行,如果你的try块失败,它就会执行catch块,然后是finally块。

此外,最好尝试使用以下结构:

using (StreamReader reader=new  StreamReader("myfile.txt"))
{
}

由于using语句被自动包装在try / finally语句中,流将自动关闭。(如果想要真正捕获异常,则需要在using语句周围加上try / catch)。

如果你读过c#,你就会明白finally块是为了优化应用程序和防止内存泄漏而设计的。

CLR并不能完全消除泄漏……如果程序无意中保留了对不需要的对象的引用,就会发生内存泄漏

例如,当您打开一个文件或数据库连接时,您的机器将分配内存来处理该事务,除非执行了dispose或close命令,否则该内存将不会被保留。但是如果在事务处理期间发生了错误,则继续执行的命令将被终止,除非它在try..最后. .块。

Catch与finally的不同之处在于,Catch的设计目的是为您提供处理/管理或解释错误的方法。把它想象成一个人告诉你“嘿,我抓住了一些坏人,你想让我对他们做什么?” 而最终的目的是确保你的资源被正确地配置。想想某人,不管有没有坏人,他都会确保你的财产仍然安全。

你应该让他们俩永远合作下去。

例如:

try
{
  StreamReader reader=new  StreamReader("myfile.txt");
  //do other stuff
}
catch(Exception ex){
 // Create log, or show notification
 generic.Createlog("Error", ex.message);
}
finally   // Will execute despite any exception
{
  reader.Close();
}

使用Try…Catch . .最后,如果您的方法知道如何在本地处理异常。异常发生在Try中,在Catch中处理,然后在Finally中完成清理。

如果你的方法不知道如何处理异常,但需要在异常发生后进行清理,请使用Try..最后

通过这种方式,异常被传播到调用方法,如果调用方法中有任何合适的Catch语句,则进行处理。如果当前方法或任何调用方法中没有异常处理程序,则应用程序将崩溃。

最后,确保在将异常传播到调用方法之前完成了本地清理。