Currently I'm in the process of writing a client class that utilizes DNS, Sockets, and SSL among other classes that love to throw exceptions. Other people will be implementing this class, so I was wondering what the best practice is for throwing exceptions.
Should I create my own custom exception so they know that it is my class throwing the exception or should I allow the classes and methods I call (DNS, Sockets, etc.) to throw their own exceptions? Currently, the code is in the hundreds of lines and growing with many different method calls. What is the best practice for throwing exceptions in this situation?
Deitel and Deitel (2019) claim that one should use built-in exceptions. Kapil (2019) recommends using custom exceptions when one creates an interface or a library, as this helps diagnose problems that have occurred in the code.
The big advantage is that it allows you to throw and exceptions that mean what you want them to mean. If you reuse an existing exception, any piece of your code that catches the exception has to deal with possibility that the actual exception wasn't thrown by your code, but by some other library party code.
If the BCL contains classes that already convey the meaning you want (ArgumentNullException
, for instance), use those.
Reserve using your own exception classes for things that are specific to your API.
If you feel that you can add information, by all means raise your own exception but do not swallow exceptions - propagate them up as inner exceptions of your own.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With