Alex Rivera | Logout

Preventing exceptions vs. catching exceptions in Java

Asked 2009-05-21T20:02:33.677
13

I am wondering how in practice other SOers tend to deal with and/or prevent exceptions.

In what situations do you prevent exceptions, and how? In what situations do you catch exceptions?

I usually prevent 'NullPointerExceptions' (and other similar ones) by, well, essentially saying if(foo!=null) {...}

I find that in most situations this is less bulky than everything involved in using a try-catch block.

I use try-catch blocks when the potential exceptions are more complex, or more numerous.

Edit
Report

3 Answers

5

Catch exceptions where you know how to deal with them.

You shouldn't check for (foo!=null) everywhere, check where foo is first used only. After that just use foo without checking. If foo suddenly becomes null after you've made sure it isn't null, you have big problems. An exception is appropriate then.

try {
   foo();
}
catch (FooException e) {
}

is a bad code smell, and should be avoided

answered 2009-05-21T21:39:09.067
3

I will check the input parameters at the beginning of a method and throw an IllegalArgumentException if they are outside what should be passed to the method. The idea being that it's a programming error and it should be fixed. Better now than when it's out in the field. If in the middle of a method I get an unexpected condition (null in a list, etc) I will log a fatal message and do a System.exit(2). Again this forces you to fix an issue vs. just logging it and moving on.

answered 2009-05-21T23:53:55.037
1

In general, if it is reasonable to do so, you should try to prevent the exception from occurring in the first place. Quite frequently, it's not reasonable or possibly flat-out impossible (especially when io in concerned), but that's what try/catch are for. In particular, this means that you should always check your pointers and your array indexes to prevent the NullPointerException and ArrayIndexOutOfBoundsException. Unless, of course, there is nothing you can do about it and would have to rethrow it anyway.

answered 2009-05-21T20:08:51.697

Your Answer