由于不会在try块内部引发异常的方法会对以下代码产生任何负面的性能影响吗?
String user;
try {
user = SomeHelper.getUserName(); //Does not throw anything explicitly
if (SomeHelper.isSomething(user)) { //Does not throw anything explicitly
user.doSomeSafeThing(this); //Does not throw anything explicitly
}
else {
user.doOtherSafeThing(this); //Does not throw anything explicitly
}
SomeOtherHelper.methodThatCanBlow(User.getCredentials(context)); //This will throw exception
} catch (Exception e) {
e.printStackTrace();
}
我相信编译器不会重构任何这些代码,因为这些方法中的任何一个都可能抛出NullPointerException,或者另一个RuntimeException并且实际上被catch块捕获。
所以我想问一下这个问题,以下代码会更有效吗?
String user;
user = SomeHelper.getUserName(); //Does not throw anything explicitly
if (SomeHelper.isSomething(user)) { //Does not throw anything explicitly
user.doSomeSafeThing(this); //Does not throw anything explicitly
}
else {
user.doOtherSafeThing(this); //Does not throw anything explicitly
}
try {
SomeOtherHelper.methodThatCanBlow(User.getCredentials(context)); //This will throw exception
} catch (Exception e) {
e.printStackTrace();
}
答案 0 :(得分:4)
由于不会在try块内部引发异常的方法会对以下代码产生任何负面的性能影响吗?
不,它不会产生任何性能影响,但是:
try
块中放入最少的代码Exception
,而是抓住特定的例外