c# exception handling, practical example. How would you do it?

前端 未结 2 1947
无人及你
无人及你 2021-02-07 16:37

I\'m trying to get better at handling exceptions but I feel like my code gets very ugly, unreadable and cluttered when I try my best to catch them. I would love to see how other

2条回答
  •  佛祖请我去吃肉
    2021-02-07 16:58

    Rule one of exception handling - do not catch exceptions you don't know how to handle.

    Catching exceptions just in order to provide nice error messages is questionable. The exception type and message already contain enough information for a developer - the messages you have provided do not add any value.

    the DataContractJsonSerializer show no exceptions on the intellisense. Does this mean the constructor will never fail? Can I be sure?

    No, you can't be sure. C# and .NET in general are not like Java where you have to declare what exceptions may be thrown.

    A third option would be to ignore all exceptions apart from the ones that would allow me to take an action like retrying the connection.

    That indeed is the best option.

    You can also add a general exception handler at the top of the application that will capture all unhandled exceptions and log them.

提交回复
热议问题