Preventing exceptions vs. catching exceptions in Java

error-handling, exception, java

Solution

In my opinion, it only makes sense to prevent a NullPointerException (for example) when a reference being null (again, for example) actually represents a valid program state. If it does not, you should not prevent it from happening, because in that case you want the program to die hard.

In Java in particular, certain exceptions descending from RuntimeException (such as IllegalArgumentException) are really meant to signal programming errors, conditions that should not happen if your program is correct. I try to follow this. If I am writing a method that places restrictions on its arguments, I will not try to avoid throwing an exception. I will throw one aggressively.

Problem

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.

Original source

Related problems