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?
2
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.
Exceptions are not for errors that can be reasonably checked. I’m also not sure why your defining a private exception type since you won’t be able to catch that exception as it propagates up. I’m also not sure why you’re creating an inner class.
Extending the RuntimeException, Exception or Throwable is not about overriding behavior. It’s about creating an exception hierarchy appropriate for your application. For example, if you’re driving a car, a low level exception might be GPSReadError which is a type of NavigationError, which is a type of AutoDriveError which is a type of VehicleException. It’s also about identifying the source of the exception. For example, a GPSReadError would not be used when checking tire pressure.
IMHO Exceptions are one area where Java could be cleaned up, with frameworks like spring throwing subclasses of RuntimeException almost exclusively. In fact, you could look at Spring’s intelligent use of RuntimeExceptions to better classify errors when using JDIBC. http://static.springsource.org/spring/docs/3.0.x/reference/jdbc.html
1
Side stepping all the “should” and “shouldn’t” arguments (which are relevant, btw).. if you do finally end up with an “inner class”, at least make it “static”:
private static class MissingPropertyException extends RuntimeException{};
Rod Johnson author of Expert One-On-One J2EE Design and Development mentioned runtime exceptions are often a better alternative to checked exceptions(Obviously many things depends on your business logic and team members).
But Rather
private class MissingPropertyException extends RuntimeException{};
you can use/design something close to NestedRuntimeException
Others have lectured on proper exception usage, so instead of repeating that, I’d suggest an alternative in form of something called an Optional:
Optional<String> optionalProperty = myMethod();
if (optionalProperty.isPresent())
// do something with it
else
// property did not exist
This approach forces the calling code to take an action in case the return value is missing. This is analogous to using throws MissingPropertyException
which also forces the caller to handle it, but I think using Optional is more explicit.
It is fine to create an ’empty’ exception subclass. Just see it as a classification.
I would stick to YAGNI though and always look for code that would actually filter on the exception type you create.
If I understand your usage, I would consider using an “IllegalStateException” for this with a good message. It’s already built into Java.
Your reasons for choosing an unchecked exception are not clear to me, but I think it would make sense on the build() method of a Builder pattern if your builder requires that one of several possible parameters be used. Please check your reasoning for using an unchecked exception against my blog post on checked vs. unchecked exceptions.