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>;
}
}
loadLibrary(String filename) method loads the dynamic library with the specified library name. A file containing native code is loaded from the local file system from a place where library files are conventionally obtained. The details of this process are implementation-dependent.
public class UnsatisfiedLinkError extends LinkageError. Thrown if the Java Virtual Machine cannot find an appropriate native-language definition of a method declared native .
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 OutOfMemoryError
means you have run out of memory and there's very little you can do about it. StackOverflowError
means that your call stack has grown too deep and there's not a lot you can do about that either.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With