2 Replies Latest reply on Mar 5, 2005 11:57 PM by Mike Duffy

    What's the deal with all the unchecked exceptions?

    Dan Christopherson Newbie

      Spec issue: None of the EntityManager methods through any checked exceptions. The javadoc for them mentions IllegalArgumentException and sometimes TransactionRequiredException. There's a lot more than that that can go wrong in persistence!

      The 'find' methods are particularly nasty - they throw ObjectNotFoundException, which is unchecked. The one case where it might be reasonable (depending on use case) to return null and not throw an exception, and it throughs an unchecked exception! A developers life would be much easier in the long run with checked exceptions: you are then forced to think about the difficult issues ahead of time, and the compiler can help you remember to take care of it. Sure you can whack something together a bit quicker if you don't have to think about what might go wrong, but if that rarely leads to robust software!

      I copied this to ejb3-feedback, but I'm hoping to you folks have some further information/explanation...

      as always, thanks,

        • 1. Re: What's the deal with all the unchecked exceptions?
          Bill Burke Master

          Personally I prefer unchecked exceptions declared in the throws cause. I hate having to catch exceptions when I'm not interested in them. I agree the spec needs to a few more exception types, but I disagree that they should be checked. Most frameworks out there (including Spring) rely on unchecked exceptions.

          • 2. Re: What's the deal with all the unchecked exceptions?
            Mike Duffy Novice

            See: Best Practices for Exception Handling

            If the client can take some alternate action to recover from the exception, make it a checked exception. If the client cannot do anything useful, then make the exception unchecked. By useful, I mean taking steps to recover from the exception and not just logging the exception.

            Moreover, prefer unchecked exceptions for all programming errors: unchecked exceptions have the benefit of not forcing the client API to explicitly deal with them. They propagate to where you want to catch them, or they go all the way out and get reported. The Java API has many unchecked exceptions, such as NullPointerException, IllegalArgumentException, and IllegalStateException. I prefer working with standard exceptions provided in Java rather than creating my own. They make my code easy to understand and avoid increasing the memory footprint of code.