使用Exception类捕获每个异常是否正确?如果不是那么什么?

Azh*_*har 3 .net c# exception-handling exception

使用Exception类捕获每个异常是否正确?如果没有,那么在try catch块中捕获异常的正确序列应该是什么?

例如

try{
       .
       .
       some code
       .
   }
   catch(Exception ex)
   {
       throw ex;
   }
Run Code Online (Sandbox Code Playgroud)

Ste*_*dit 15

不,这是错的.

  1. 仅仅再次投掷是没有意义的.

  2. 它不正确地重新抛出,导致丢失堆栈跟踪.重新抛出的正确方法(当重新抛出是有道理的时候)就是:throw;

  3. 如果你想捕获一个异常,然后抛出另一个异常,你应该保留第一个异常作为第二个的内部异常.这是通过将其传递给构造函数来完成的.

底线:只捕捉您知道如何处理的例外情况.

  • @liho:这不是他所要求的,但这是他需要知道的事情之一.我相信,总的来说,我的答案解决了他的问题. (2认同)

Tim*_*ell 5

如果您在捕获之后立即抛出异常 - 这与完全没有try/catch块的情况基本相同.

捕获可能发生的特定异常.

例如,您尝试保存文件但由于某种原因无法写入:

    try
    {
      SaveFile();
    }
    catch(FileIsReadOnlyException)
    {
      //do whatever to recover
    }
    catch(Exception ex)
    {
      //If we hit the generic exception, we're saying that we basically have 
      //no idea what went wrong, other than the save failed.
      //
      //Depending on the situation you might want to sink and log it, i.e. do nothing
      //but log it so you can debug and figure out what specific exception handler to
      //add to your code -- or you might want to try to save to a temporary file and
      //exit the program.
      //
      //If you were UpdatingAnAdvertisement() or doing something else non-critical
      //to the functioning of the program, you might just let it continue and
      //do nothing.
      //
      //In that case, you can just omit the generic catch.
    }
Run Code Online (Sandbox Code Playgroud)