Java etiquette - when to use try/catch and when to use if

statik213

Golden Member
Oct 31, 2004
1,654
0
0
Say you want to do this:
double d, x , y;
....
d = x / y;

and you can't say if y == 0 or not.
Should you do this:

if( y == 0){
....
} else {
d = x/y;
}

or

try{
d = x/y;
} catch (ArithmeticException e){
...
}

or when dealing with objectsthat maybe null should you check if it is null first an `if` or `catch` the NullPointerException when you 'use' it?
Which is better and for what reason?



 

Barnaby W. Füi

Elite Member
Aug 14, 2001
12,343
0
0
IMO the 'if' is simpler and more straightforward. Exceptions should be used in "exceptional" circumstances, or at least when stack unwinding is useful (and it's not in a simple situation like this).
 

znaps

Senior member
Jan 15, 2004
414
0
0
Yep, only use Exceptions for exceptional circumstances. Using the try/catch is slower, and less informative to other coders.
 

TerryMathews

Lifer
Oct 9, 1999
11,464
2
0
As was explained in my Java + Relational Databases class, you only need to use try/catch when going outside the JVM - ie accessing a normal piece of the hardware.
 

Barnaby W. Füi

Elite Member
Aug 14, 2001
12,343
0
0
Originally posted by: TerryMathews
As was explained in my Java + Relational Databases class, you only need to use try/catch when going outside the JVM - ie accessing a normal piece of the hardware.

That doesn't sound right. Accessing a bad reference throws an exception, doesn't it?
 

replicator

Senior member
Oct 7, 2003
431
0
0
Important guideline when catching exceptions is to first know what you want to do with it. If you don't know, then there isn't much point in catching it.

As others stated, it should be for exceptional circumstances. If you can prevent a divide by zero, then you should handle it using standard syntax instead of wrapping it in a try/catch block. I/O is a good example of when you should use it.
 

TerryMathews

Lifer
Oct 9, 1999
11,464
2
0
Originally posted by: BingBongWongFooey
Originally posted by: TerryMathews
As was explained in my Java + Relational Databases class, you only need to use try/catch when going outside the JVM - ie accessing a normal piece of the hardware.

That doesn't sound right. Accessing a bad reference throws an exception, doesn't it?

Are there bad references inside the virtual machine? We only glossed over the surface.
 

Barnaby W. Füi

Elite Member
Aug 14, 2001
12,343
0
0
Originally posted by: TerryMathews
Originally posted by: BingBongWongFooey
Originally posted by: TerryMathews
As was explained in my Java + Relational Databases class, you only need to use try/catch when going outside the JVM - ie accessing a normal piece of the hardware.

That doesn't sound right. Accessing a bad reference throws an exception, doesn't it?

Are there bad references inside the virtual machine? We only glossed over the surface.

Yep, NullPointerException I believe. I'm sure there are a ton of others, hell I've never even coded a line of java in my life.
 

TerryMathews

Lifer
Oct 9, 1999
11,464
2
0
Originally posted by: BingBongWongFooey
Originally posted by: TerryMathews
Originally posted by: BingBongWongFooey
Originally posted by: TerryMathews
As was explained in my Java + Relational Databases class, you only need to use try/catch when going outside the JVM - ie accessing a normal piece of the hardware.

That doesn't sound right. Accessing a bad reference throws an exception, doesn't it?

Are there bad references inside the virtual machine? We only glossed over the surface.

Yep, NullPointerException I believe. I'm sure there are a ton of others, hell I've never even coded a line of java in my life.

Hmm, I don't know. I thought the JVM was designed specifically so those types of errors wouldn't occur while working inside the JVM. At any rate, these are the two things I know:

1) What I quoted from my professor above.
2) The compiler flags code where you have a function that throws an exception, and you don't catch it.
 

akubi

Diamond Member
Apr 19, 2005
4,392
1
0
Originally posted by: BingBongWongFooey

Yep, NullPointerException I believe. I'm sure there are a ton of others, hell I've never even coded a line of java in my life.

you are right (you never coded in java?!?)

for example, if you just declare an object without constructing it and try to use a method you'll get runtime null ref exceptions.

another common exception (for newbies) is if you try to access an element beyond an array's boundary.

tons more
 

znaps

Senior member
Jan 15, 2004
414
0
0
Originally posted by: TerryMathews
Originally posted by: BingBongWongFooey
Originally posted by: TerryMathews
Originally posted by: BingBongWongFooey
Originally posted by: TerryMathews
As was explained in my Java + Relational Databases class, you only need to use try/catch when going outside the JVM - ie accessing a normal piece of the hardware.

That doesn't sound right. Accessing a bad reference throws an exception, doesn't it?

Are there bad references inside the virtual machine? We only glossed over the surface.

Yep, NullPointerException I believe. I'm sure there are a ton of others, hell I've never even coded a line of java in my life.

Hmm, I don't know. I thought the JVM was designed specifically so those types of errors wouldn't occur while working inside the JVM. At any rate, these are the two things I know:

1) What I quoted from my professor above.
2) The compiler flags code where you have a function that throws an exception, and you don't catch it.


Either you misunderstood your professor, or he is just wrong. There are two different types of Exceptions - checked and unchecked (Runtime). You have to deal with checked exceptions at some point, but you do not have do deal with unchecked/runtime exceptions.

An example of an unchecked exception is NullPointerException - the most common one you'll see in Java. An example of a checked exception if FileNotFoundException, which you need to catch and deal with if you're trying to access a File (this is what I think you're referring to in point 2)
 

statik213

Golden Member
Oct 31, 2004
1,654
0
0
Hmmm.. my earlier reply did not post....

Anywayz, thanks a lot guys, the consensus is clear. Exceptions are really neat and useful esp. the stackTrace that comes along with it.... I personaly don't find a try/catch block less readble than an if/else if block.... I actually find it more readable 'cos most exception have v.v. descriptive names.....
 

TerryMathews

Lifer
Oct 9, 1999
11,464
2
0
Originally posted by: znaps
Either you misunderstood your professor, or he is just wrong. There are two different types of Exceptions - checked and unchecked (Runtime). You have to deal with checked exceptions at some point, but you do not have do deal with unchecked/runtime exceptions.

Probably just wrong. I quoted him, word for word, out of my notes. He's an assistant professor and a masters student, and SQL is his thing not really Java.
 

kamper

Diamond Member
Mar 18, 2003
5,513
0
0
Originally posted by: znaps
Originally posted by: TerryMathews
Originally posted by: BingBongWongFooey
Originally posted by: TerryMathews
Originally posted by: BingBongWongFooey
Originally posted by: TerryMathews
As was explained in my Java + Relational Databases class, you only need to use try/catch when going outside the JVM - ie accessing a normal piece of the hardware.

That doesn't sound right. Accessing a bad reference throws an exception, doesn't it?

Are there bad references inside the virtual machine? We only glossed over the surface.

Yep, NullPointerException I believe. I'm sure there are a ton of others, hell I've never even coded a line of java in my life.

Hmm, I don't know. I thought the JVM was designed specifically so those types of errors wouldn't occur while working inside the JVM. At any rate, these are the two things I know:

1) What I quoted from my professor above.
2) The compiler flags code where you have a function that throws an exception, and you don't catch it.


Either you misunderstood your professor, or he is just wrong. There are two different types of Exceptions - checked and unchecked (Runtime). You have to deal with checked exceptions at some point, but you do not have do deal with unchecked/runtime exceptions.

An example of an unchecked exception is NullPointerException - the most common one you'll see in Java. An example of a checked exception if FileNotFoundException, which you need to catch and deal with if you're trying to access a File (this is what I think you're referring to in point 2)
Don't forget Errors :)

There are two subclasses of Throwable, Error and Exception. Exceptions, of course, mean that something is wrong with your program. Errors, for the most part, mean that something is wrong with the virtual machine (out of memory, class missing, using incompatible version of a class...). Errors should almost never be caught, usually because you aren't capable of handling them.
 

znaps

Senior member
Jan 15, 2004
414
0
0
Originally posted by: kamper

Don't forget Errors :)

There are two subclasses of Throwable, Error and Exception. Exceptions, of course, mean that something is wrong with your program. Errors, for the most part, mean that something is wrong with the virtual machine (out of memory, class missing, using incompatible version of a class...). Errors should almost never be caught, usually because you aren't capable of handling them.

I didn't forget them, we weren't talking about them :)

I think 'class missing and incompatible versions of a class' would produce Exceptions, not Errors.

 

kamper

Diamond Member
Mar 18, 2003
5,513
0
0
http://java.sun.com/j2se/1.5.0/docs/api...ml?java/lang/NoClassDefFoundError.html
http://java.sun.com/j2se/1.5.0/docs/api...lang/IncompatibleClassChangeError.html :)

There was talk of stuff going on inside the virtual machine so I figured bringing up Errors was appropriate. I think an unchecked Exception would be reasonable for these instances, since you might very well want to trap and ignore them for the sake of system stability, especially since you don't want people just catching Throwable. Try it sometime though, you get an Error.
 

znaps

Senior member
Jan 15, 2004
414
0
0
My bad on the incompatible class. I was thinking of ClassNotFoundException for the 'missing class' issue. I think these errors frequently get wrapped in a RuntimeException though, so you can trap them like you say.
 

Brett

Senior member
Oct 15, 1999
377
0
76
Originally posted by: Snapster
Originally posted by: notfred
Use exceptions only when you need to. They're slow and awkward.

Bingo

there are times when try/catch is much faster than ifs... for example, if you know that an exception marks the end of a loop, there are times (i.e., loops are large enough to warrant it) where while(true) inside a try is better than trying to do
while(some_logic_to_stop_before_exception)... since the difference in time between the evulation of true and the extra logic being done to get the true/false value of the second while will eventually take more time than the initial cost for a try/catch.

But I agree, exceptions should be used in very few circumstances, in most applications, its better to make sure the program logic works correctly and doesnt require try/catch.
 

kamper

Diamond Member
Mar 18, 2003
5,513
0
0
Originally posted by: Brett
Originally posted by: Snapster
Originally posted by: notfred
Use exceptions only when you need to. They're slow and awkward.

Bingo

there are times when try/catch is much faster than ifs... for example, if you know that an exception marks the end of a loop, there are times (i.e., loops are large enough to warrant it) where while(true) inside a try is better than trying to do
while(some_logic_to_stop_before_exception)... since the difference in time between the evulation of true and the extra logic being done to get the true/false value of the second while will eventually take more time than the initial cost for a try/catch.

But I agree, exceptions should be used in very few circumstances, in most applications, its better to make sure the program logic works correctly and doesnt require try/catch.
Wtf? Heard of break or continue? Wouldn't you still need the conditional logic to decide whether or not to throw the exception?

I think I'm completely missing your point. Could you provide code?
 

znaps

Senior member
Jan 15, 2004
414
0
0
I believe he's saying that for arrays of sufficiently large sizes, using a try-catch(ArrayIndexOutOfBoundsException) will be less expensive than check the bounds of the array for every iteration.

Anybody want to run some quick tests? :)
 

kamper

Diamond Member
Mar 18, 2003
5,513
0
0
Originally posted by: znaps
My bad on the incompatible class. I was thinking of ClassNotFoundException for the 'missing class' issue. I think these errors frequently get wrapped in a RuntimeException though, so you can trap them like you say.
Why would they get wrapped? The only way I think of how that would happen is if someone purposely catches the Error and wraps in a RuntimeException but I've never heard of anybody going to that amount of trouble just to make it more catchable.
 

znaps

Senior member
Jan 15, 2004
414
0
0
Originally posted by: kamper
since you might very well want to trap and ignore them for the sake of system stability

So here you are saying that someone might very well want to trap them, and now you're saying that nobody would every want to go to the trouble? I'm not sure I follow, you appear to be contradicting yourself.

 

kamper

Diamond Member
Mar 18, 2003
5,513
0
0
Well, usually when you're trapping for stability you pick a single point which should never fail, no matter what happens inside. You wrap it in a try {} catch (Exception e) {} and then just log the error and move on. This is very handy for stopping NullPointerExceptions from being too disruptive. And you almost never actually throw another Exception from that catch.

Catching Errors related to classloading and wrapping them in RuntimeExceptions is a totally different situation. With that you still have no guarantee that what you throw will be caught, you're just making it more likely and I've never seen anybody go to the trouble. Doing it properly pretty much means catching only LinkageErrors (as all the rest should not be caught unless you really mean to do something about them) and I don't think I've ever even seen LinkageError being referenced in any code. I'd be interested in hearing about it though, if you've seen it done.