Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, Class-specific Exceptions vs. Standard Exceptions

Tags:

java

exception

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.

like image 284
Carl Avatar asked Jan 12 '10 19:01

Carl


People also ask

What are the two types of exceptions in Java which are the differences between them?

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.

What are the three types of exceptions?

There are three types of exception—the checked exception, the error and the runtime exception.

What are the two kinds of exceptions?

There are mainly two types of exceptions in Java as follows: Checked exception. Unchecked exception.


1 Answers

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.

like image 53
Greg Beech Avatar answered Sep 21 '22 16:09

Greg Beech