Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create custom exception or use built-in exceptions?

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?

like image 608
krs1 Avatar asked Aug 09 '10 19:08

krs1


People also ask

Should I create custom exceptions?

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.

What is the advantage of creating your own custom exception class?

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.


1 Answers

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.

like image 93
Oded Avatar answered Oct 05 '22 09:10

Oded