Catching base Exception class in .NET

前端 未结 16 1947
心在旅途
心在旅途 2020-12-05 19:06

I keep hearing that

catch (Exception ex)

Is bad practise, however, I often use it in event handlers where an operation may for example go

16条回答
  •  死守一世寂寞
    2020-12-05 19:24

    You should catch the exceptions related to what you are doing. If you look at the methods you call, you will see what exceptions they throw, and you want to stay more specific to those. You should have access to know what exceptions may be thrown by the methods you call, and handle them appropriately.

    And... better than having one big try catch, do your try and catch where you need the catch.

    try {
       myThing.DoStuff();
    }
    catch (StuffGoneWrongException ex) {
       //figure out what you need to do or bail
    }
    

    Maybe not quite this closely packed, but it depends on what you are doing. Remember, the job isn't just to compile it and put it on someones desktop, you want to know what breaks if something did and how to fix it. (Insert rant about tracing here)

提交回复
热议问题