try/catch as conditional

StackOverflow 中的相关讨论 : http://stackoverflow.com/questions/8621762/java-if-vs-try-catch-overhead

 

You really should not use try/catch and if interchangeably.

try/catch is for things that go wrong that are outside of your control and not in the normal program flow. For example, trying to write to a file and the file system is full? That situation should typically be handled with try/catch.

if statements should be normal flow and ordinary error checking. So, for example, user fails to populate a required input field? Use if for that, not try/catch.

 There is more overhead even if the exception is never thrown.

 

但是,比较容易实现的 isLong(String str) 还是使用了 try/catch:

1 public boolean isLong(String str) {
2     try {
3         Long.parseLong(str);
4     } catch(Exception e) {
5         return false;
6     }
7     return true;
8 }

 

这个冲突怎么解决?

posted @ 2016-01-04 20:22  一切不期而至  阅读(127)  评论(0编辑  收藏  举报