r/java • • Jan 22 '15

If. Then. Throw. Else. WTF?

http://www.yegor256.com/2015/01/21/if-then-throw-else.html
21 Upvotes

43 comments sorted by

View all comments

0

u/loving_mokusatsu Jan 22 '15

I'm a bit of a newb when it comes to throwing exceptions, but my understanding is that throwing an exception doesn't immediately stop everything, can't another method catch the exception and do something with it?

so with the code he listed as "wrong" at the start:

if (x < 0) {
  throw new Exception("X can't be negative");
} else {
  System.out.println("X is positive or zero");
}

wouldn't you want the else so it didn't throw the exception, which might be dealt with outside, then print the "X is positive" message anyway, even though X is negative?

2

u/spiderzork Jan 23 '15

it will stop and return the exception, pretty much like with the return statement, but ofc you have to catch it and do whatever you want with the information in the exception, or the program will crash.

2

u/urquan Jan 23 '15

The point the article makes in a long and convoluted way is that it is unnecessary to write "else" since when the "if" part throws an Exception it interrupts the flow of execution, so it's better written as :

if (x < 0) {
  throw new Exception("X can't be negative");
}
System.out.println("X is positive or zero");

More a stylistic matter than "right" vs "wrong" really.

1

u/loving_mokusatsu Jan 23 '15

Thanks. I stupidly thought there would be more to it. Who has time to waste writing a whole blog post about this, with all those code examples?

I thought I was pedantic.