• Post Reply Bookmark Topic Watch Topic
  • New Topic

Do I need to catch any of these exception in my code ?

 
ben oliver
Ranch Hand
Posts: 375
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Usig EJB 3.

For code like

query.getResultList();

I saw the APi shows it throws

NoResultException - if there is no result
NonUniqueResultException - if more than one result
IllegalStateException - if called for a Java Persistence query language UPDATE or DELETE statement

But all these 3 exceptions are sub class of "RuntimeException". So it seems we do NOT need to catch them, correct ?

But I feel weird that we just let such code go without handling its exception...


Similarly for code like

EntityMangerInstance.createNativeQuery(....)

the API shows it also throws a "IllegalStateException" which is sub class of "Runtiem exception" too. So we can ignore it too ?
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 35719
412
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ben,
You can ignore any runtime exception including all of those. Whether you should is a different story. Your choices are:

1) Ignore it and let the exception propogate
2) Catch the exception and wrap it in one more useful to the caller
3) Catch the exception and handle it with logic

We don't know the context of your call so can't recommend which is best.
 
ben oliver
Ranch Hand
Posts: 375
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jeanne Boyarsky wrote:Ben,
You can ignore any runtime exception including all of those. Whether you should is a different story. Your choices are:

1) Ignore it and let the exception propogate
2) Catch the exception and wrap it in one more useful to the caller
3) Catch the exception and handle it with logic

We don't know the context of your call so can't recommend which is best.


Thanks.

1) you said I can "ignore and let it propogate". How ? Do you mean I can just do nothing and at the signature of the method add "throws these new exception " ? i.e. don't catch any of them in the code but throw them in the method signature.

2. can I catch all these exception and throw a customized exception ?
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 35719
412
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1) Yes. But then the caller needs to deal with them and probably isn't more qualified than you.
2) Yes. This is often preferred. It shows the caller that "something" went wrong in your layer and provides a single exception to check.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!