Java Exceptions – The Suffix Exception on Exception Names

exceptionsjavanaming

Specifying a suffix of Exception on exception classes feels like a code smell to me (Redundant information – the rest of the name implies an error state and it inherits from Exception). However, it also seems that everyone does it and it seems to be good practice.

I am looking to understand why this is good practice.

I have already seen and read the question why do exceptions usually have the suffix exception in the class name

The question is for PHP and while the responses are probably valid for Java. Are there any other arguments or is it really as simple as explicitly differentiating them?

If we take the examples from the previous question – could there really be classes in java with the name FileNoFound that is not an exception? If there could be, does it warrant suffixing it with Exception ?

Looking at a quick hierarchy in eclipse of Exception, sure enough, the vast majority of them do have the suffix of exception, but there are a few exceptions. javassist is an example of a library that seems to have a few exceptions without the suffix – e.g. BadByteCode, BadHttpRequest etc.

BouncyCastle is another lib with exceptions like CompileError

I've googled around a bit as well with little info on the subject.

Best Answer

Landei's answer is a good one, but there's also the grammatical answer. Class names should be nouns. What is an "OutOfMemory"? What is a "FileNotFound"? If you think of "Exception" as the noun, then the descriptor is the adjective specifying it. It's not just any Exception, it's a FileNotFoundException. You shouldn't need to catch an OutOfMemory any more than you'd go to the store to buy a "blue".

This also shows up if you read your code as a sentence: "Try doing ..., and catch OutOfMemory Exceptions"

Related Topic