有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java中的C++“Goto”替代

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

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

多谢各位


共 (1) 个答案

  1. # 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);
    }