Preventing exceptions vs. catching exceptions in J

2019-01-25 09:23发布

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.

13条回答
放我归山
2楼-- · 2019-01-25 10:20

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

查看更多
登录 后发表回答