Best practices for handling exceptions in C#

Published on:

When creating customized exception lessons, all the time derive from the Exception class, not from the ApplicationException class. One of many causes for that is that an occasion of ApplicationException is thrown solely by the appliance and by no means by the runtime. Everytime you throw an occasion of ApplicationException in your code, you merely enhance the decision stack with out including a lot worth.

Be aware that exceptions are bubbled as much as the upper stage within the methodology name hierarchy, and it isn’t observe to deal with exceptions in all of the layers of your utility. It’s best to deal with an exception as excessive up within the name hierarchy as you may. For instance, you may eat an exception within the presentation layer and show applicable messages to the consumer to speak the precise error that has occurred.

- Advertisement -

It’s a good observe to make use of particular exceptions like FileNotFoundException and IOException when writing exception handlers after which a common catch block on the finish with the Exception class. This may be certain that you get a transparent understanding of the precise error that has occurred. As Microsoft’s documentation states: “The ApplicationException class doesn’t present data as to the reason for exceptions. In most situations, cases of this class shouldn’t be thrown. In circumstances the place this class is instantiated, a human-readable message describing the error needs to be handed to the constructor.”

See also  Samsung Galaxy Ring vs Ultrahuman Ring Air: Which subscription-free smart ring wins?
- Advertisment -

Related

- Advertisment -

Leave a Reply

Please enter your comment!
Please enter your name here