• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Insight to exception handling please

 
E Robb
Ranch Hand
Posts: 111
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying to learn about exception handling and am having a hard time getting my mind around the big picture. Can I get some feedback on the code below. Should the throws have DataNotFoundException, AccessDeniedException AND the try catch with each message defined? Or is it ok to just have throws Exception and each of the additional exceptions in the try catch.

Is there a better or cleaner way to write these exceptions than the way I have below?


 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15441
41
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For checked exceptions, you need either a "throws" clause in the method declaration (line 11), or you need to catch the exceptions and handle them - not both.

The "throws" clause just means: this method might throw this exception. If you're catching those exceptions inside the method (and not throwing them further), you don't need the "throws" clause.

In general, specifying "throws Exception" (explicitly saying that the method can throw any kind of exception) is bad practice. A "throws" clause should be as specific as possible about what exceptions it throws. If you declare your method with "throws Exception" then the users of your method are forced to deal with any kind of exception that might happen, which will make it harder for them to handle errors.
 
E Robb
Ranch Hand
Posts: 111
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey Jesper thanks for the help. Is this correct based on what you are saying?

I should either do this:


or I should do this:


But I should not use both throws and catch in the same statement?

If I define all the throws in the class and not the catch

public long getLogonAuth(String domainName) throws DataNotFoundException, AccessDeniedException, Exception

How do I get my error messages to come out correctly? My import error messages are e.getMessage1() instead of what you would see for standard (Exception e) getMessage()

Sorry If I am being obtuse. I just want to understand. Based on what you are saying I should do one or the other but not both.

Thanks,
Earl

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic