Search code examples
javaserial-portnoclassdeffounderrorrxtx

Prevent NoClassDefFoundError from crashing program


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 one that throws the error


Solution

  • 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;
    }