java.lang.Exception vs. rolling your own exception

mcjabberz picture mcjabberz · Oct 26, 2008 · Viewed 11.8k times · Source

At what point would you create your own exception class vs. using java.lang.Exception? (All the time? Only if it will be used outside the package? Only if it must contain advanced logic? etc...)

Answer

JaredPar picture JaredPar · Oct 26, 2008

I think you need to ask yourself a slighly different question "What advantage does creating a new exception give me or developers who use my code?" Really the only advantage it gives you or other people is the ability to handle the exception. That seems like an obvious answer but really it's not. You should only be handling exceptions that you can reasonably recover from. If the exception you throw is a truly fatal error why give developers a chance to mis-handle it?

More in depth discussion: Custom exceptions: When should you create them?