Monday, October 7, 2024

Greatest practices for dealing with exceptions in C#



At all times derive from the Exception class

When creating customized exception courses, 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 improve the decision stack with out including a lot worth.

Deal with exceptions on the highest degree

Notice that exceptions are bubbled as much as the upper degree within the technique name hierarchy, and it’s not a very good follow to deal with exceptions in all of the layers of your utility. It is best to deal with an exception as excessive up within the name hierarchy as you’ll be able to. For instance, you’ll be able to eat an exception within the presentation layer and show acceptable messages to the consumer to speak the precise error that has occurred.

Use predefined exceptions and clear error messages

It’s a good follow to make use of particular exceptions like FileNotFoundException and IOException when writing exception handlers after which a basic catch block on the finish with the Exception class. This may be sure 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 eventualities, cases of this class shouldn’t be thrown. In circumstances the place this class is instantiated, a human-readable message describing the error must be handed to the constructor.”

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Stay Connected

0FansLike
3,912FollowersFollow
0SubscribersSubscribe
- Advertisement -spot_img

Latest Articles