Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

throwing exceptions

 
Aly Gilani
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 657
Clojure Spring VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

[ June 27, 2005: Message edited by: Steve Morrow ]
 
Aly Gilani
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Aly Gilani
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your reply Ernest!
 
peter cooke
Ranch Hand
Posts: 317
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sorry - I decided my lack of sleep warrent retracting my statements.
[ June 27, 2005: Message edited by: peter cooke ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic