Java Exceptions – Better Way to Define an Exception Thrown by a Method

exceptionsjava

I know how to define exceptions and all, but I'm not sure if the way I'm doing it is the most intuitive and readable by another users.

I have a very simple method I've written that I want to throw an exception, because it's easier then manually checking return values; the method is private and there is no way need to define a public Exception type. None of the existing Java exceptions fit the error exactly, so I'm trying to figure out what type of exception I want to throw here?

I don't want to just throw a RuntimeException, I only want to catch my specific exception I throw, all other Exceptions should propagate up. I figured I would define a little inner class for my exception. However, i don't really need to overwrite anything in the RuntimeException class, I just want to catch and and print it's message. So now I have a line that says something like

private class MissingPropertyException extends RuntimeException{};

This does nothing but allow me to catch only the exception I'm intentionally throwing while ignoring the rest. Is this good syntax? it feels odd to define a inner class without implementing anything within it. Is there a way to do this elegantly without creating an empty inner class?

Best Answer

I'm going to assume that there are situations where it is reasonable to throw exceptions.

I'm also going to assume that this is a situation where it is reasonable to use exceptions. (The fact that this is "internal" to your code does not alter this. And you cannot reasonably infer that exceptions are in appropriate based on the proposed exception name ... @Jarrod Roberson note!)

So the question is whether it is reasonable to declare a private exception class. To that I would say "Yes", assuming that there is no existing exception class that is suitable.

The only riders I would make is that if there is any chance that the exception might "leak", then:

  • you should declare a constructor so that the exception has a reason String, and
  • you should declare it as public ... so that any javadoc for the exception appears in the published API documentation.