Why Re-throw Exceptions?

后端 未结 13 1725
借酒劲吻你
借酒劲吻你 2020-12-13 00:25

I\'ve seen the following code many times:

try
{
    ... // some code
}
catch (Exception ex)
{
    ... // Do something
    throw new CustomException(ex);

            


        
13条回答
  •  有刺的猬
    2020-12-13 01:08

    Actually there is a difference between

    throw new CustomException(ex);
    

    and

    throw;
    

    The second will preserve the stack information.

    But sometimes you want to make the Exception more "friendly" to your application domain, instead of letting the DatabaseException reach your GUI, you'll raise your custom exception which contains the original exception.

    For instance:

    try
    {
    
    }
    catch (SqlException ex)
    {
        switch  (ex.Number) {
            case 17:
            case 4060:
            case 18456:
               throw new InvalidDatabaseConnectionException("The database does not exists or cannot be reached using the supplied connection settings.", ex);
            case 547:
                throw new CouldNotDeleteException("There is a another object still using this object, therefore it cannot be deleted.", ex);
            default:
                throw new UnexpectedDatabaseErrorException("There was an unexpected error from the database.", ex);
        } 
    }
    

提交回复
热议问题