开发者

Prevent NoClassDefFoundError from crashing program

开发者 https://www.devze.com 2023-02-21 08:03 出处:网络
I\'m writing a Java program for my work-study program which relies on the RXTX serial drivers. It is running well on my testing machines, however I have noticed that when run on a machine that does no

I'm writing a Java program for my work-study program which relies on the RXTX serial drivers. It is running well on my testing machines, however I have noticed that when run on a machine that does not have RXTX installed the application fails to open. In the console it has thrown the "java.lang.NoClassDefFoundError" exception for "gnu/io/CommPortIdentifier". I put this into a try/catch so that it would instead display a message to the user telling them to check their RXTX driver installation rather than simply exiting the program. However it doesn't actually do this, still just closes out as soon as it hits that line. Any ideas? Thanks!

EDIT: Some code for ya:

Enumeration sportsAll = null;
Vector<String> v = new Vector();
SerialPort sp;
CommPortIdentifier portID;
String currString;

try {
    sportsAll= CommPortIdentifier.getPortIdentifiers();
} catch (Exception e) {
    v.addElement("Check RXTX Drivers");
}

The "sportsAll= CommPortIdentifier" line is the o开发者_运维问答ne that throws the error


It's because you try to catch Exception which is not a parent class for NoClassDefFoundError see JavaDoc. Catch the concrete exception class instead.

Better approach is to check for availability of the driver itself. For example:

private static boolean isDriverAvailable() {    
    boolean driverAvailable = true;

    try {
        // Load any class that should be present if driver's available
        Class.forName("gnu.io.CommPortIdentifier");
    } catch (ClassNotFoundException e) {
        // Driver is not available
        driverAvailable = false; 
    }

    return driverAvailable;
}


java.lang.Error states

An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions.

And java.lang.NoClassDefFoundError extends LinkageError (which extends Error). You shouldn't catch any Error at all in a try-catch block.

You will have to write a code to check if RXTX is installed first before executing your rest of the code.


This is because NoClassDefFoundError extends Error (not Exception).

The best way would be to catch NoClassDefFoundError itself. You can also catch either Error or Throwable.

0

精彩评论

暂无评论...
验证码 换一张
取 消