【问题标题】:"goto" alternative in JavaJava中的“goto”替代方案
【发布时间】:2013-11-18 15:21:10
【问题描述】:

在 Visual C++ 代码中,我曾经编写一些宏来检查函数的返回值是否不是预期的,转到 Exit 标签。像这样的:

HRESULT hr = S_OK;
IF_FALIED_EXIT(boo());
...
Exit:
  if(FAILED(hr)){ print error message }
  return hr;

这是为了防止程序崩溃,并且可以随时处理异常。我的问题是,在 Java 中我们是否推荐这样的代码风格,还是应该在大多数情况下使用 try/catch?

谢谢

【问题讨论】:

  • 从来没有人推荐goto。如果你想在 Java 中处理异常,请使用 try/catch 块
  • 我见过的 C++ 中没有 GOTO 错误处理模式,无法通过 java 中的 try/catch/finally 进行复制。
  • C++ 不需要宏加上 goto 解决方法。它有 RAII。使用它。

标签: java c++ error-handling coding-style


【解决方案1】:

这在 Java 中是特别不鼓励的。见Features Removed From C and C++

在 Java 中,您可以执行一些类似的操作,例如,请参阅以下基本示例,该示例使用标记的 break 进行提前转义:

// a Class is handed in to create a new instance of with basic reflection

construct_and_add: if (clazz != null) {

    try {
        Object obj = clazz.newInstance();

    } catch (Exception e) {
        System.err.println("Error <" + e.getClass().getName()
            + "> in reflective instantiation: " + e.getMessage());

        break construct_and_add;
    }

    somewhereElse.add(obj);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-26
    • 2012-07-26
    • 2013-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多