wood burning stoves*
The moose likes Java in General and the fly likes throwing exceptions Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "throwing exceptions" Watch "throwing exceptions" New topic
Author

throwing exceptions

Aly Gilani
Greenhorn

Joined: Jul 20, 2004
Posts: 7
Hello all,

I've heard from many people that we should not throw exceptions explicitly as they are really expensive. So we shouldn't do something like this if we dont want to execute the code after the nullCheck:



The other way we can accompish this is by using statement blocks (which are nasty), something like:



My question is: in such instances when we dont want to execute the remainder of the code in a method, what would be the best way of doing it?

Thanks in advance,

Aly
[ June 27, 2005: Message edited by: Aly Gilani ]
Steve Morrow
Ranch Hand

Joined: May 22, 2003
Posts: 657


[ June 27, 2005: Message edited by: Steve Morrow ]
Aly Gilani
Greenhorn

Joined: Jul 20, 2004
Posts: 7
Thanks for your reply Steve.

But isnt it against good coding practices to use return statements in the middle of a method?

And also we would end up with a lot of return statements if we are dealing with multiple params. Any other way to deal with it?

Thanks in advance.

Aly
[ June 27, 2005: Message edited by: Aly Gilani ]
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Originally posted by Aly Gilani:

But isnt it against good coding practices to avoid using "returns" in the middle of a method?


This is an outdated idea. What's bad is writing very long methods with confusing control flow. If you write a method with less than a dozen lines of code, there's absolutely nothing wrong with a return in the middle. But you can always invert the logic and execute the rest of the body inside the if, right?


And also we would end up with a lot of return statements if we are dealing with multiple params. Any other way to deal with it?


You should not throw an exception during normal execution. That means, for example, don't use an ArrayIndexOutOfBoundException to terminate a for loop.
If you need to report a programming error -- and a null parameter usually is -- then by all means, go ahead and throw an exception. That's what they're there for.


[Jess in Action][AskingGoodQuestions]
Aly Gilani
Greenhorn

Joined: Jul 20, 2004
Posts: 7
Thanks for your reply Ernest!
peter cooke
Ranch Hand

Joined: Mar 16, 2004
Posts: 317
sorry - I decided my lack of sleep warrent retracting my statements.
[ June 27, 2005: Message edited by: peter cooke ]

CIAO Peter M. Cooke
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: throwing exceptions