Question: “If any error occurs when running the getInstance() method … and I still want the getInstance() method return the right result. How to achieve this?”
Short answer: you can’t guarantee it.
There are a large number of conditions which can throw a Throwable
There are 2 main types (subclasses) of Throwable
: Exception
and Error
.
Exception
is used to indicate a condition which may arise in the application to prevent normal flow of execution, and the application may catch and correct the situation before continuing. Some forms of Exception (checked exceptions) have to be caught eventually.
Error
is used to indicate a seriously abnormal condition from which the application cannot be expected to recover, the cause of which is probably beyond the application’s control. You can catch an Error but there’s not much point as the situation probably cannot be recovered.
As you can see, if your getInstance()
throws an error, there’s nothing you can do whilst the application is running. You only have a sporting chance of recovery if an Exception occurs.
solved Make singleton pattern code stronger [closed]