Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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?

share|improve this question
1  
you are mis-using exceptions, what you are describing is not exceptional, it is expected behavior apparently from your description. this can be checked before had easily and handled without having to incur the overhead of raising an exception. –  Jarrod Roberson Mar 9 '13 at 3:11
2  
@Jarrod Roberson - perhaps this code is well beyond the point where it should have guaranteed the property to exit. You don't know. This particular exception may indicate programmer error. Murdering example. –  Joppe Mar 9 '13 at 12:12

7 Answers 7

up vote 3 down vote accepted

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.
share|improve this answer

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

share|improve this answer
    
I'm doing the exact same 'thing' dozens of times when loading properties. any one of those properties missing will prevent my code from functioning and require a complete shutdown. I could load eachp roperty, check if it's valid, and report an error individually; which would grow tedious with lots of ugly boiler plate code. Or I could just throw an exception. The exception will be caught in my own classes so it won't propigate up; it just saves the hassle of individually checking existance of every property. –  dsollen Mar 11 '13 at 15:45

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

share|improve this answer

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.

share|improve this answer

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.

share|improve this answer

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{};
share|improve this answer

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.