有没有更好的解决方案(不)在尝试捕获后继续



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

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

外面有更漂亮的东西吗?

有没有更好的解决方案(不)在尝试捕获后继续

预期方法是编写应在 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.
}

即使它是一个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 提供的代码将起作用。

您可以简单地忽略异常并记录异常以供参考:

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) {....

你可以使用 retun; break; 或者可能使用 System.exit()

最新更新