File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes when to use catch block and when to use throws Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "when to use catch block and when to use throws" Watch "when to use catch block and when to use throws" New topic
Author

when to use catch block and when to use throws

amit taneja
Ranch Hand

Joined: Mar 14, 2003
Posts: 810
hi ranchers,
can any body please tell me whent to use catch block and when to use throws
in our daily programming practice
i know both are alternatives to each other but still what are the factors which decides ?

kindly reply in details


Thanks and Regards, Amit Taneja
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 42932
    
  68
They're not at all alternatives to each other, but rather opposites, kind of. throws throws a new exception, while try/catch/finally handles exceptions. You might want to read chapter on exception in the Sun Java Tutorial.
Remko Strating
Ranch Hand

Joined: Dec 28, 2006
Posts: 893
Mostly I use the try catch block for errors which i can solve within a method call, such as when a user preferred setting is not found then use the default one or when a database procedure reports an error then log the error.

If the cause of the error cannot be solved within the method itself then I will report that error to the calling method within the stack. This is done with a throws.

It's also possible to combine both errors. If you have a database error like there is no connection available, you can solve this error in the method which you use the connect to the database and then you can report this error to the e calling method, so the method knows that there are problems with the connection so that the remaining code couldn't run.

I hope this helps a bit
[ July 16, 2007: Message edited by: Remko Strating ]

Remko (My website)
SCJP 1.5, SCWCD 1.4, SCDJWS 1.4, SCBCD 1.5, ITIL(Manager), Prince2(Practitioner), Reading/ gaining experience for SCEA,
Bob Ruth
Ranch Hand

Joined: Jun 04, 2007
Posts: 320
Just another comment....

You use a catch block to handle an error condition that has occurred in the execution of some method.

You use a throw when an error condition has been noted and want to flag that the error has occurred.

Your use of catch{} will most likely exceed your use of throw().

If you are writing some method code that needs to check some condition.... lets say here is an example ( a dumb one.... but an example!) :

Lets say that you are writing a method that accepts two arguments, divides the first one by the second one, and returns the result to the caller. BUT..... according to your design specification.... argument two can ONLY BE the number 23!!! In other words.... every time someone calls you they MUST pass a 23 in to argument 2.

I would expect that your code would test the value and, if it is NOT 2, it would throw an exception.

I know this was a goofy example but the idea is, if you are writing routines that are checking for specific conditions, specific states, specific values, specific responses, and they are not right... THAT might be when you would want to throw an exception.

Most of the time, you will just be coding catch blocks to handle the exceptions from below.


------------------------
Bob
SCJP - 86% - June 11, 2009
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
[Ulf]: They're not at all alternatives to each other, but rather opposites, kind of. throws throws a new exception, while try/catch/finally handles exceptions. You might want to read chapter on exception in the Sun Java Tutorial.

Sure they're alternatives. If something in your method throws a checked exception, what do you do about it? The two basic alternatives are to catch it, or declare the exception in a throws clause. (Or catch and throw a different exception, declared with throws, or for unchecked exceptions, you can omit throws entirely.) If catch has an opposite, I think it's throw, not throws. And I think that's what you've described above: throw throws a new exception (or more rarely, rethrows an existing exception), whereas throws merely notifies callers that the exception may be thrown.

I agree with Remko's and Bob's answers. Also I would add that I think many beginning programmers overuse catch in places where a throws would be better. Of then if a method experiences some problem, then that needs to be communicated to the method(s) that called the method with the problem. E.g. consider the method

And another method that uses it:

If getEmployee() fails to get an employee, what happens? It will return null, and the processPayroll() method will throw a NullPointerException. And a bunch of subsequent employees will not get their checks printed because of a problem with one employee. In this case, processPayroll() probably should have checked to see if emp was null. However that's the sort of thing that's easy to forget when you use a method. If instead you declare that getEmployee() throws a checked exception, then callers will be more likely to consider what to do if something goes wrong. E.g.

Or perhaps better (since a SQLException is not very informative to other methods that don't know what getEmployee does internally):
In either case, letting getEmployee() throw a checked exception can increase the chances that the caller will think about how to handle that situation intelligently. You may also want to consider making EmployeeNotFound an unchecked exception, but that's a much longer discussion, probably not good for JiG Beginner.


"I'm not back." - Bill Harding, Twister
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 42932
    
  68
Originally posted by Jim Yingst:
[Ulf]: They're not at all alternatives to each other, but rather opposites, kind of.

Sure they're alternatives. If something in your method throws a checked exception, what do you do about it? The two basic alternatives are to catch it, or declare the exception in a throws clause.


My bad. I read a bit too quickly and thought the question was about "throw" (as in "throw new Exception"), while it is actually about "throws" (as in "throws Exception").
amit taneja
Ranch Hand

Joined: Mar 14, 2003
Posts: 810
ya earlier I was surprissed by the fact, because i do myself is scjp 1.4 with 90% but got confused what to use ? in what scienerio.

so the conclusion is that

when we use throws declaration with method, the caller method takes responsibility to handle the exception and the program stops ??? !!

but in case of catch block handling program does not get stop.. if handled properly...
Bob Ruth
Ranch Hand

Joined: Jun 04, 2007
Posts: 320
My apologies. I, too, blazed RIGHT through that one answering what I THOUGHT I read.

I think that selection (catch versus throws) boils down to the level where you want to handle the particular exception.

This is just for the sake of discussion but my thinking would be along these lines: if the impact of the exception is limited, meaning, it is NOT a show-stopper, and that we can "recover", "retry", or "maintain control" at the deeper level, then handle it there. The more critical the impact is to the overall processing, let the handling fall back to an earlier method where you can either recover at that level, or "fall on your sword!".
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Two quick reasons to catch an exception - there may be more

1) You want to do something different because of the exception. Maybe "reading the database threw an exception so I'll try reading a file." If you're going to give up without trying something different, you might as well let it fly.

2) You want to "hide" information about what went wrong. I have a generic DataAccessor interface that has a database implementation, a remote web service call implementation and an in-memory implementation. I don't want that to throw SQLExceptions because I don't want callers to know when I'm using a database. And I can't change it to throw IOExceptions when I add my file based implementation. So my implementations catch SQLException and IOException and throw DataAccessException.

These conflict a bit. #1 says let it go, #2 says convert the type. #2 is used less often, but always wins the argument.


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: when to use catch block and when to use throws