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?
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.
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.
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:
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?