Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Okay to catch UnsatisfiedLinkError to fall back to a different DLL on a call to System.LoadLibrary?

Tags:

java

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>;
    }
}
like image 227
Stevens Miller Avatar asked Feb 02 '12 16:02

Stevens Miller


People also ask

What is System loadLibrary?

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.

What is UnsatisfiedLinkError?

public class UnsatisfiedLinkError extends LinkageError. Thrown if the Java Virtual Machine cannot find an appropriate native-language definition of a method declared native .


1 Answers

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.

like image 102
Joni Avatar answered Sep 29 '22 02:09

Joni