Alex Rivera | Logout

Java, Class-specific Exceptions vs. Standard Exceptions

Asked 2010-01-12T19:39:27.120
16

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.

Edit
Report

2 Answers

18

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.

  1. When to throw different types of exception? Throw a different type of exception for each symptom that can be programmatically handled differently.

  2. 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.

answered 2010-01-12T19:46:19.340
1

I'd use explicitly defined exceptions to give the client code more control. If the client wants to, they can catch IllegalArgumentException as in your example above. If they need more control, they can catch individual types of exceptions. Consider, for example, a method that could throw two subclasses of IllegalArgumentException. If you don't subclass, you have to do string parsing or some other nonsense to determine the actual cause of the thrown exception. User-defined types solves this issue.

answered 2010-01-12T19:45:01.123

Your Answer