EDIT
Please note my question is more to understand if there is any best practice around it. The problem I am describing can be tackled many way, in fact I am handling it by throwing Runtime Exception. But is it the best practice? or should we fall back to more conventional ways of Singleton creation using a static method and decoupling exception from object creation
I am using enum to instantiate a singleton as prescribed in Effective Java
public enum MailApp {
INSTANCE;
private Gmail mailService;
private MailApp() {
try {
mailService = GoogleMailAppFactory.getGmailService();
} catch (IOException e) {
throw new AssertionError(e);
}
}
The problem is if I add throws like following
public enum MailApp {
INSTANCE;
/** Application name. */
private Gmail mailService;
private MailApp() throws IOException {
mailService = GoogleMailAppFactory.getGmailService();
}
This will not compile saying Unhandled Exception
I have taken a look at How to throw an exception from an enum constructor?
I could not find any conclusive answer. So my question: What are the best practices for this? Is throwing an AssertionError only way forward?
Thanks for your help
Edit
My "MailApp" is only valid if we have a valid email service. In short I dont want to create an empty object. Could you please throw some light why this might be a bad idea and how this should be approached?