File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Insight to exception handling please Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Insight to exception handling please" Watch "Insight to exception handling please" New topic

Insight to exception handling please

E Robb
Ranch Hand

Joined: Aug 27, 2010
Posts: 111
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

Joined: Aug 16, 2005
Posts: 15094

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.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
E Robb
Ranch Hand

Joined: Aug 27, 2010
Posts: 111
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.


I agree. Here's the link:
subject: Insight to exception handling please
It's not a secret anymore!