| Author |
Return statement in Catch block
|
neha singh tomar
Greenhorn
Joined: Apr 14, 2009
Posts: 5
|
|
I started working on JDBC recently. As I was trying to understand the same, searched for a few programs on internet. I noticed in one program that the programmer has written a "return" statement in catch clause. I could not understand the significance of return in catch block.
Could you please help me understand this.
Example to the block:
catch (ClassNotFoundException e) {
System.out.println("Failed to load the driver");
e.printStackTrace();
return;
}
|
 |
Winston Gutkowski
Bartender
Joined: Mar 17, 2011
Posts: 4747
|
|
neha singh tomar wrote:Could you please help me understand this.
I think it might be better if you posted all the code for the method, because from what you've shown, there's no particular reason to put the return statement inside the block (although there's also nothing particularly wrong with it).
Winston
|
Isn't it funny how there's always time and money enough to do it WRONG?
|
 |
neha singh tomar
Greenhorn
Joined: Apr 14, 2009
Posts: 5
|
|
Thanks for the reply, Winston.
This has been copied from http://www.techlabs4u.com/2010/07/java-sample-code-to-connect-to-db2.html.
Please find the code below.
|
 |
Anayonkar Shivalkar
Bartender
Joined: Dec 08, 2010
Posts: 1295
|
|
Hello neha singh tomar,
Welcome to CodeRanch!
Pleae UseCodeTags so that code will be easier to read.
As you can see, in catch block, the code prints the stack trace. But if you don't put return statement there, code will proceed in the same method.
Now, in the given code, even if IBM DB2 driver is not found, without the return statement, code will follow saying 'driver loaded successfully' and attempting to get the connection, which we don't want.
The return statement simply returns from the method, without executing any further code.
Another approach for the same would be throwing your own exception in such cases.
I hope this helps.
|
Regards,
Anayonkar Shivalkar (SCJP, SCWCD, OCMJD)
|
 |
Winston Gutkowski
Bartender
Joined: Mar 17, 2011
Posts: 4747
|
|
neha singh tomar wrote:Please find the code below.
First: please UseCodeTags (←click). (Edit: too late )
However, I see that the example is actually part of a main() method, so in it's case, the return statement will cause the program to exit. It seems a bit redundant to me, since you could achieve the same thing by simply declaring the method to throw ClassNotFoundException and forgetting the try...catch altogether; but maybe the authors were trying to provide a more user-friendly message.
In lots of these cases, there's no real 'right' or 'wrong' way to do things; just ones that make sense.
Winston
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32654
|
|
But don’t use == true of == false, etc. Write if (b)... or if (!b)...
The == in that case is awkward to read, error-prone because you might write = by mistake.
|
 |
 |
|
|
subject: Return statement in Catch block
|
|
|