Reputation: 11331
In Visual C++ code, I used to write some macros to check if a function's return value is not expected, goto the Exit label. Something like this:
HRESULT hr = S_OK;
IF_FALIED_EXIT(boo());
...
Exit:
if(FAILED(hr)){ print error message }
return hr;
This is to prevent the program from being crash and can always handle exceptions. My question is, in Java do we recommend code style like this, or should we use try/catch for most of the cases?
Thank you
Upvotes: 0
Views: 279
Reputation: 37845
This is specifically discouraged in Java. See Features Removed From C and C++.
In Java there are some things you can do that are similar, for example see the following basic example that uses a labelled break for an early escape:
// 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);
}
Upvotes: 1