Catching the Un-Catchable

I know it is bad practice to catch java.lang.NoClassDefFoundError.  Today, however, I did need a way to deal with it because I have this annoying habit of wanting everything else to work even when some non-critical piece is broken.

This case was a matter of a third-party security jar that would throw up rather than out when it could not find its properties file. No matter how many catches I had wrapped around the call to the method in the jar, the java.lang.NoClassDefFoundError would bubble up as a big render issue in the JSP.  I am only using this jar to get the user display name, so it isn’t like my application is not secure if I don’t have their name to make them feel special.

After several annoying and pointless approaches, I came up with the following (ugly-but-effective) solution:

try //the Security class relies on this property file but pukes if not found, 
    //so we test for it here
{
   FileInputStream in = new FileInputStream("security.properties");
   in.close();
}
catch(Exception e)
{
   System.out.println("security.properties is missing from classpath");
   return personInfo;
}
//...go use the third-party class that depends on the file having proven it is there

This allowed the application to continue running and not falling apart at the header just because one file was missing. It is one thing to have a bug that is minor, another when that bug becomes something that users pick up the phone about.

Facebooktwitterredditlinkedinmail
© Scott S. Nelson