Why catch and rethrow an exception in C#?

前端 未结 17 645
遥遥无期
遥遥无期 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:05

    While many of the other answers provide good examples of why you might want to catch an rethrow an exception, no one seems to have mentioned a 'finally' scenario.

    An example of this is where you have a method in which you set the cursor (for example to a wait cursor), the method has several exit points (e.g. if () return;) and you want to ensure the cursor is reset at the end of the method.

    To do this you can wrap all of the code in a try/catch/finally. In the finally set the cursor back to the right cursor. So that you don't bury any valid exceptions, rethrow it in the catch.

    try
    {
        Cursor.Current = Cursors.WaitCursor;
        // Test something
        if (testResult) return;
        // Do something else
    }
    catch
    {
        throw;
    }
    finally
    {
         Cursor.Current = Cursors.Default;
    }
    

提交回复
热议问题