Announcement Announcement Module
Collapse
No announcement yet.
Downgrading RuntimeException to Checked Exception Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Downgrading RuntimeException to Checked Exception

    I use Hibernate as the persistence mechanism. Let's say I have a transaction that is dependent upon another persistent object which is loaded during that transaction. In the "load" method for the child object we use something like this:
    Code:
        public User getUser(String username) {
            User user = (User) getHibernateTemplate().get(User.class, username);
            if (user == null) {
                throw new ObjectRetrievalFailureException(User.class, username);
            }
            return user;
        }
    Since the ObjectRetrievalFailureException is a runtime exception, Spring automagically rolls back the transaction. I realize I could just return null from the getUser method or return a checked exception.. but what if I don't want to for whatever reasons. Is there any way for me to downgrade the RuntimeException to a checked Exception so that I can declaratively determine whether or not to rollback?

    -Matt

  • #2
    Using Checked Exception willl require you to change the method declaration (add a throw) and use a try / catch whenever you call your method. A better solution would be to use the -/+ ObjectRetrievalFailureException in the transaction attribute for your method.

    HTH

    Comment


    • #3
      I'm not sure I understand what you want to do. Do you want to throw the exception but still commit the transaction? In that case, here are something that may help you:

      http://www.springframework.org/docs/...n.html#d0e4693
      You can specify what behavior exceptions cause declaratively (both checked and unchecked). So for a particular method, you could say that ObjectRetrievalFailureException causes commit. For example:

      Code:
      <prop key="getUser">PROPAGATION_REQUIRED,+ObjectRetrievalFailureException</prop>

      Comment


      • #4
        Strange Behavior

        I tried to specify +Exception as a test (before I did my first post) and it still rolled the exception back. Do I have to specify the exact Exception? I thought any subclass would be honored... maybe I should get off the crack pipe. I will try it again to see if that works.

        -Matt

        Comment


        • #5
          <prop key="getUser">PROPAGATION_REQUIRED,+ObjectRetrieva lFailureException</prop>
          None of the examples I have seen on this uses a package name prefix on the exception. Is this correct? I thought I had to use:

          Code:
          <prop key="getUser">PROPAGATION_REQUIRED,+com.example.ObjectRetrievalFailureException</prop>
          Is it just that exceptions in examples tend to be declared in the default package?

          Comment

          Working...
          X