In Java we have the ability to write our own Exceptions.
Why would I want/need to do this? What are the upsides or advantages of doing so?
Why should I create my Exception, rather than adding to the catch of a standard Exception?
In Java we have the ability to write our own Exceptions.
Why would I want/need to do this? What are the upsides or advantages of doing so?
Why should I create my Exception, rather than adding to the catch of a standard Exception?
You should write your own exception classes if you answer yes to any of the following questions; otherwise, you can probably use someone else’s.
Taken from "2. Creating custom Exception" in this article.
If you need to throw an exception for an unrecoverable situation (in other words, you don't plan to catch and handle it), then do not create your own exception type.
However, there are legitimate (though quite rare) cases where exceptions actually are used to signal recoverable exceptional circumstances. In those cases it is the best option to create your own exception type to represent your domain-specific circumstance.
BTW when I say "handle", I mean more than log or return a general failure response. The handling code should "live with" the exception and apply some business logic to proceed.
You don't necessarily need to, but if you're creating for example a library, you might want to create your own exception hierarchy to go with it.
Well named custom exceptions will provide additional information, but often you'll find existing exceptions that will meet your requirements (you don't need to make your own IllegalArgumentException
or similar exception types).