如果在try块内

时间:2017-08-01 14:38:24

标签: java if-statement try-catch

如果满足IF语句中的条件,我想执行我的方法 callmethod 。否则它应该执行catch块。但是在实现过程中,如果不满足条件,则不会进入catch块。

try{
if(count==0)
callmethod();
}
catch (Exception e){
System.out.println(e);
}

2 个答案:

答案 0 :(得分:2)

这是方法的一个很好的应用:

try {
  if (count == 0) {
    callOneMethod();
  }
  else {
    callOtherMethod();
  }
catch (Exception e) {
  callOtherMethod();
}

这样你没有任何重复的代码,并且在非特殊情况下你没有做异常的事情。

答案 1 :(得分:1)

由于你试图点击catch块,如果你的参数不符合你需要抛出异常(即count!= 0)。

示例:

try {
    if(count==0){
        callmethod();
    } else {
        throw new SomeException("some message");
    }
}
catch (Exception e){
    System.out.println(e);
}
相关问题