How to catch java.lang.NoClassDefFoundError?

Ashish picture Ashish · Nov 16, 2011 · Viewed 24.9k times · Source

I made an application which take elf file(*.a and *.o) and give list of methods name, but if someone renames any file into *.a or *.o then it will show:

Exception occurred during event dispatching:
java.lang.NoClassDefFoundError: org/eclipse/core/resources/IWorkspaceRunnable
    at org.eclipse.cdt.utils.AR.<init>(AR.java:237)
    at com.lge.windowELF.ElfBinaryArchive.<init>(ElfBinaryArchive.java:24)
    at com.lge.windowELF.ELFParserLibraryFile.createBinaryArchive(ELFParserLibraryFile.java:230)
    at com.lge.windowELF.ELFParserLibraryFile.<init>(ELFParserLibraryFile.java:46)
    at com.lge.windowELF.ELFWrapper.<init>(ELFWrapper.java:36)
    at com.lge.windowELF.ELF_UIIntegrated.actionPerformed(ELF_UIIntegrated.java:510)
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)

In this situation I want to give some warning message. This exception is not caught by try/catch.

Answer

Tomasz Nurkiewicz picture Tomasz Nurkiewicz · Nov 16, 2011

NoClassDefFoundError is a subclass of Error and not an Exception. Hence you need to use:

try {
  new org.eclipse.cdt.utils.AR();
}
catch(NoClassDefFoundError e) {
  //handle carefully
}

in your code. Note that you shouldn't ever catch Error or Throwable. Also make sure that you surround as little code as possible with this catch as this exception should not typically by caught.

UPDATE: Also are you sure you want to catch this exception? It is very rare and I can't imagine how do you want to handle it. Maybe you should just add a JAR with IWorkspaceRunnable class to your CLASSPATH?