[ACCEPTED]-What is the general rule of thumbs for creating an Exception in Java?-exception

Accepted answer
Score: 22

The Java Specialists wrote a post about Exceptions in Java, and in it they list 8 a few "best practices" for creating 7 Exceptions, summarized below:

  • Don't Write 6 Own Exceptions (there are lots of useful 5 Exceptions that are already part of the 4 Java API)

  • Write Useful Exceptions (if you 3 have to write your own Exceptions, make 2 sure they provide useful information about 1 the problem that occurred)

Score: 16

Don't do what the developers at my company 31 did. Somebody created an [sic] InvalidArguementException 30 that parallels java.lang.IllegalArgumentException, and 29 we now use it in (literally) hundreds of 28 classes. Both indicate that a method has 27 been passed an illegal or inappropriate 26 argument. Talk about a waste...

Joshua Bloch 25 covers this in Effective Java Programming Language Guide [my bible of first resort 24 on Best Practices] Chapter 8. Exceptions Item 42: Favor the use of standard exceptions. Here's a bit of what 23 he says,

Reusing preexisting exceptions has 22 several benefits. Chief among these, it 21 makes your API easier to learn and use because 20 it matches established conventions with which programmers are already familiar [my emphasis, not Bloch's]. A close second is that programs using 19 your API are easier to read because they 18 aren't cluttered with unfamiliar exceptions. Finally, fewer 17 exception classes mean a smaller memory 16 footprint and less time spent loading classes.

The 15 most commonly reused exception is IllegalArgumentException. This 14 is generally the exception to throw when 13 the caller passes in an argument whose value 12 is inappropriate. For example, this would 11 be the exception to throw if the caller 10 passed a negative number in a parameter 9 representing the number of times some action 8 were to be repeated.

That said, you should 7 never throw Exception itself. Java has a well-chosen, diverse 6 and well-targeted bunch of built-in exceptions 5 that cover most situations AND describe the 4 exception that occurred well enough so that 3 you can remedy the cause.

Be friendly to 2 the programmers who have to maintain your 1 code in the future.

Score: 8

My rule of thumb is when the client (the 11 caller) might reasonably want to do something 10 different, depending on the type of exception 9 thrown, the additional exception types are 8 warranted. More often than not, however, the 7 extra exception types are not needed. For 6 instance, if the caller is writing code 5 like

try {
} catch (ExceptionType1 ex1) {
     // do something useful
} catch (ExceptionType2 ex2) {
     // do the exact same useful thing that was done in the block above

then clearly the additional exception 4 types are not needed. All too often I see 3 (or am forced to write) code like this because 2 the code being called was overzealous in 1 its creation of new exception types.

Score: 7

If I can't find an exception that has a 2 name describing what type of error was caused 1 then I make my own.

That's my rule-o-thumb.

Score: 4

Basically, each job deserves an own exception. When 19 you catch exceptions, you don't distinguish 18 different instances, like you would normally 17 do with objects, therefore you need different 16 subtypes. Using too many custom exceptions 15 is a case which I see hardly occurring.

One 14 advice would be to create exceptions as 13 needed, and if it becomes apparent that 12 one exception type is a duplicate of another, refactor 11 the code by merging the two. Of course it 10 helps if some thought goes into structuring 9 exceptions from the beginning. But generally, use 8 custom exceptions for all cases that have 7 no 1:1 correspondence to existing, situation-specific 6 exceptions.

On the other hand, NullPointerExceptions and IndexOutofBoundsExceptions might 5 actually often be appropriate. Don't catch 4 these, though (except for logging) as they're 3 a programming error which means that after 2 throwing them, the program is in an undefined 1 state.

Score: 3

My own rule of thumb:

I never throw Exception, except 8 in unit tests when what you throw is irrelevant 7 and theres no reason to spend any extra 6 time on it.

I create my own custom exception 5 type for errors occuring in my custom business 4 logic. This exception type is used as much 3 as possible for recasting other exceptions, except 2 in cases where it makes sense for the client 1 to have visibility into what actually occurred.

Score: 2

While creating your own exception:

  • All exceptions 6 must be a child of the Throwable Class

  • If you want to write 5 a checked exception that is automatically 4 enforced by the Handle or Declare Rule, you 3 need to extend the Exception Class

  • If you want to write 2 a runtime execption, you need to extend 1 the Runtime Exception Class.

Score: 0

Don't eat exceptions, throw them https://stackoverflow.com/a/921583/1097600

Avoid creating your own exception. Use the 2 below ones that are already there.


Throw 1 unchecked exceptions.


public void validate(MyObject myObjectInstance) {
    if (!myObjectList.contains(myObjectInstance))
        throw new NoSuchElementException("object not present in list");

More Related questions