I've been updating an existing library to throw exceptions to help improve debugging by people using the library.
At first, I thought I'd define exceptions specific to each class, however it turns out most of those exceptions are simply extensions of existing runtime exceptions (e.g., FooNegativeIntArgumentException extends IllegalArgumentException
, FooNullBarException extends NullPointerException
) with specific messages.
What are the trade-offs of defining new exceptions vs. using existing ones? Are there any conventions/best-practices?
Also, given the need for backwards compatibility, most (if not all) of these exceptions are runtime exceptions.
Difference Between Checked and Unchecked Exceptions in Java To summarize, the difference between a checked and unchecked exception is: A checked exception is caught at compile time whereas a runtime or unchecked exception is, as it states, at runtime.
There are three types of exception—the checked exception, the error and the runtime exception.
There are mainly two types of exceptions in Java as follows: Checked exception. Unchecked exception.
Here's my take on why we have different types of exception and when to create custom exception types (note: this uses .NET types as examples but the same principles apply to Java and any other language that uses structured error handling). It's probably too long to post here as a complete answer so I'll just post the two key extracts.
When to throw different types of exception? Throw a different type of exception for each symptom that can be programmatically handled differently.
When to create custom exception types? Create a custom exception type when you need to annotate the exception with additional information to aid in the programmatic handling of the symptom.
In your case it doesn't sound like your custom exception types are filling a gap in the symptoms that can be conveyed using standard exceptions, and they aren't adding any additional information for programmatic handling, so don't create them. Just use standard ones instead.
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