Why catch and rethrow an exception in C#?

前端 未结 17 641
遥遥无期
遥遥无期 2020-11-22 14:56

I\'m looking at the article C# - Data Transfer Object on serializable DTOs.

The article includes this piece of code:

public static string Se         


        
17条回答
  •  有刺的猬
    2020-11-22 15:17

    C# (before C# 6) doesn't support CIL "filtered exceptions", which VB does, so in C# 1-5 one reason for re-throwing an exception is that you don't have enough information at the time of catch() to determine whether you wanted to actually catch the exception.

    For example, in VB you can do

    Try
     ..
    Catch Ex As MyException When Ex.ErrorCode = 123
     .. 
    End Try
    

    ...which would not handle MyExceptions with different ErrorCode values. In C# prior to v6, you would have to catch and re-throw the MyException if the ErrorCode was not 123:

    try 
    {
       ...
    }
    catch(MyException ex)
    {
        if (ex.ErrorCode != 123) throw;
        ...
    }
    

    Since C# 6.0 you can filter just like with VB:

    try 
    {
      // Do stuff
    } 
    catch (Exception e) when (e.ErrorCode == 123456) // filter
    {
      // Handle, other exceptions will be left alone and bubble up
    }
    

提交回复
热议问题