At startup, I want my Java program to load a DLL that should be on the path defined by java.library.path. However, if that DLL is missing, I want my program to fall back to loading a different DLL. System.LoadLibrary throws an UnsatisfiedLinkError if it can’t find the DLL file. UnsatisfiedLinkError is a subclass of Error, not of Exception. Lots of commentary suggests that it is bad practice to catch Error. Is this a case where it is okay to do something like this?
try
{
System.loadLibrary("myLibrary");
}
catch (UnsatisfiedLinkError e)
{
try
{
System.load(<a fully qualified path to my fall-back library>);
}
catch (UnsatisfiedLinkError e)
{
<report that even the fall-back library didn't load>;
}
}
In this case it’s perfectly acceptable. In fact it’s the only way to do what you want to do.
In general it’s bad practice to catch Errors because there is nothing you can do to recover from them and the application may be in an unpredictable state afterwards. For example
OutOfMemoryErrormeans you have run out of memory and there’s very little you can do about it.StackOverflowErrormeans that your call stack has grown too deep and there’s not a lot you can do about that either.