Why is try {…} finally {…} good; try {…} catch{} bad?

后端 未结 20 2400
执笔经年
执笔经年 2020-11-28 01:30

I have seen people say that it is bad form to use catch with no arguments, especially if that catch doesn\'t do anything:

StreamReader reader=new  StreamRead         


        
20条回答
  •  不知归路
    2020-11-28 01:42

    While the following 2 code blocks are equivalent, they are not equal.

    try
    {
      int i = 1/0; 
    }
    catch
    {
      reader.Close();
      throw;
    }
    
    try
    {
      int i = 1/0;
    }
    finally
    {
      reader.Close();
    }
    
    1. 'finally' is intention-revealing code. You declare to the compiler and to other programmers that this code needs to run no matter what.
    2. if you have multiple catch blocks and you have cleanup code, you need finally. Without finally, you would be duplicating your cleanup code in each catch block. (DRY principle)

    finally blocks are special. The CLR recognizes and treats code withing a finally block separately from catch blocks, and the CLR goes to great lengths to guarantee that a finally block will always execute. It's not just syntactic sugar from the compiler.

提交回复
热议问题