Reputation: 1249
How to handle exceptions within Enum instances in Java? I have an enum class as follows:
public enum TagEnum {
EDIT_ACCESS("feature.edit", GlobalAccess.getEditStatus());
private String key;
private Boolean featureStatus;
private TagEnum(String key, Boolean status) {
this.key=key;
this.featureStatus=status;
}
}
In above scenario getEditStatus()
method of GlobalAccess
class throws Exception:
public static Boolean getEditStatus() throws Exception {
...
}
Above TagEnum
enum gave a compilation error because the enum instance cannot handle GlobalAccess.getEditStatus()
method. Please guide me on how to pass java methods that throws exceptions, as an argument inside an Enum instance.
Upvotes: 0
Views: 8523
Reputation: 13012
You can't handle an exception during class member declaration and declaring an enum
in this sense is much the same as declaring a class.
You will have to move the GlobalAccess.getEditStatus()
call into a block, constructor, or method to handle any exceptions that are thrown. As an example, you could move it into the constructor like so;
private TagEnum(String key) {
this.key=key;
try{
this.featureStatus = GlobalAccess.getEditStatus();
} catch(Exception e) {
// Handle the exception here.
}
}
Alternatively Initialization Blocks were created for more or less exactly this issue. To allow you handle logic, errors and exceptions during class(or enum) member declaration.
Upvotes: 1
Reputation: 48837
You could implement a dedicated method which will be able to handle this exception, e.g.:
public enum TagEnum {
EDIT_ACCESS("feature.edit") {
@Override
protected Boolean initFeatureStatus() {
try {
return GlobalAccess.getEditStatus();
} catch (Exception e) {
// handle it there
return null;
}
}
};
private String key;
private Boolean featureStatus;
private TagEnum(String key) {
this.key = key;
this.featureStatus = initFeatureStatus();
}
protected abstract Boolean initFeatureStatus();
}
Upvotes: 0