Java 有没有更好的解决方案可以在方法中尝试捕获后继续(而不是)呢?

Java 有没有更好的解决方案可以在方法中尝试捕获后继续(而不是)呢?,java,methods,try-catch,Java,Methods,Try Catch,现在,我的解决方案如下所示: public void method() { int number; boolean continue = true; try { number = parseInt(this.something); } catch (NumberFormatException e) { //some code continue = false; } if (continue) { //more code } }

现在,我的解决方案如下所示:

public void method() {
  int number;
  boolean continue = true; 
  try {
     number = parseInt(this.something);
  } catch (NumberFormatException e) {
     //some code
     continue = false;
  }

  if (continue) {
    //more code
  }
}

外面有更漂亮的吗

即使是
void
方法,也可以使用
return然后将退出该方法。因此,您的“问题”的完美解决方案是只使用
return
并按如下方式删除
if

public void method() {
    int number;
    try {
        number = parseInt(this.something);
    } catch (NumberFormatException e) {
        //some code
        return;
    }
    //more code
}

如果对象设置不正确(this.something未设置),则最好在调用代码中抛出然后捕获。如果您刚刚返回,调用方可能会认为方法已成功完成。否则,Aidin提供的代码将起作用。

您可以使用retun;打破或者可能是System.exit()

有没有更好的解决方案可以在方法中尝试捕获后继续(而不是)呢

预期的方法是编写应在try块内跳过的代码:

public void method() {
  try {
     int number;
     number = parseInt(this.something);
    //more code
  } catch (NumberFormatException e) {
    // log exception
    // do things to recover from the error if possible
    // maybe rethrow `e` or throw another exception
  }
  // avoid to write some code here, usually it is wrong.
}

您只需忽略该异常并记录该异常以供参考:

public void method() {

    int number;

    try {
        number = parseInt(this.something);
    } catch (Exception ignored) {
        // here could be some System.out.println or a logging API
    }
}
但如果您有一个返回值,只需返回null并评估您的结果是否为null

public Integer method() {

    try {
        return parseInt(this.something);
    } catch (Exception ignored) {
        // here could be some System.out.println or a logging API
    }

    return null;
}

Integer number = method();
if (number != null) {....

使用
return
continue
在Java BTW中不是一个保留字吗?但是,仅基于此代码示例,您似乎问错了问题。如果您在早期验证了this.something
是一个整数,那么您一开始就不会有这个问题。大多数情况下,您希望尽早失败,避免在代码中引入不必要的复杂性。不能在那里使用
break
,并且使用
System.exit()
非常糟糕,因为
method()
的调用方可能想做其他事情。
//某些代码仍然可以分配适当的值,离开对象的字段是一种良好的状态。但一定要小心。