public class MyClass
{
private static final SomeClass myVar;
static
{
Object obj = null; // You could use SomeClass, but I like Object so you can reuse it
try
{
obj = new SomeClass(...);
}
catch(WhateverException err)
{
// Possibly nested try-catches here if the first exception is recoverable...
// Print an error, log the error, do something with the error
throw new ExceptionInInitializerError(err);
}
finally
{
myVar = (SomeClass) obj;
}
}
}
假设上游无法捕获ExceptionInInitializationError或一般异常,则程序不应尝试使用myVar。但是,如果这些被捕获并且程序没有结束,那么您需要编写代码来监视和处理myVar是否为空(或者对全部结束感到满意NullPointerExceptions
)。
我不确定有没有好方法来处理这个问题。