Trying to understand exceptions in C#

前端 未结 7 1773
日久生厌
日久生厌 2020-12-11 21:18

I do not really use any try/catches in my code ever but I\'m trying to break that habit and now get in to using exceptions.

I figure the most important place to have

7条回答
  •  没有蜡笔的小新
    2020-12-11 21:50

    Ok, first...

    ... This iss not KeynotFoundException, it should be ArgumentException.... the Argument provided is not valid.

    The documentation clearly states:

    The exception that is thrown when the key specified for accessing an element in a collection does not match any key in the collection.

    Compare that with:

    The exception that is thrown when one of the arguments provided to a method is not valid

    Now:

    Also, why do people say not to do catch (Exception e)?

    Becasue this swallows the exception and makes it impossible to have central error handling / logging in place. ONLY handle exception you expect, UNLESS it is a catch / close something or log it / rethrow (i.e. throw;). Then have a central appdomain handler that gets every uncaptured exceptin and logs it ;) It can not handle anything - because exceptions at that level are unexpected,. It should basically write the excption to a file and be done, possibly with a UI (application has t obe restartet).

提交回复
热议问题