在 Visual C++ 代码中,我曾经编写一些宏来检查函数的返回值是否不是预期的,转到 Exit 标签。像这样的东西:
HRESULT hr = S_OK;
IF_FALIED_EXIT(boo());
...
Exit:
if(FAILED(hr)){ print error message }
return hr;
这是为了防止程序崩溃,并且可以随时处理异常。我的问题是,在 Java 中,我们是否推荐这样的代码风格,还是应该在大多数情况下使用 try/catch?
谢谢
在 Visual C++ 代码中,我曾经编写一些宏来检查函数的返回值是否不是预期的,转到 Exit 标签。像这样的东西:
HRESULT hr = S_OK;
IF_FALIED_EXIT(boo());
...
Exit:
if(FAILED(hr)){ print error message }
return hr;
这是为了防止程序崩溃,并且可以随时处理异常。我的问题是,在 Java 中,我们是否推荐这样的代码风格,还是应该在大多数情况下使用 try/catch?
谢谢
这在 Java 中是特别不鼓励的。请参阅从 C 和 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);
}