Women in Technology

Hear us Roar

  Best Practices for Exception Handling
Subject:   Runtime Exception is not informative
Date:   2007-03-07 19:48:45
From:   johnydep
Exceptions have been developed to give more flexibility to the developer while debugging the code

here is sample method. Intention of the code is to raise exception
}catch (ClassNotFoundException ce){

following error was displayed
java.lang.ClassNotFoundException: jdbc.odbc at java.net.URLClassLoader.findClass(URLClassLoader.java:241) at java.lang.ClassLoader.loadClass(ClassLoader.java:516) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:460) at java.lang.ClassLoader.loadClass(ClassLoader.java:448) at java.lang.Class.forName1(Native Method) at java.lang.Class.forName(Class.java:142) at test.exechandle.TestAddition.getdatabase(TestAddition.java:29) at test.exechandle.TestExecption.main(TestExecption.java:22)

Now the code was modified to throw the run time exception
}catch (ClassNotFoundException ce){
throw new RuntimeException();
java.lang.RuntimeException at test.exechandle.TestAddition.getdatabase(TestAddition.java:31) at test.exechandle.TestExecption.main(TestExecption.java:22)
Exception in thread "main"

if we compare both the exceptions i would see the complie time exception is more informative rather than runtime.
So is that advisiable that we ommit the complie time exception

Full Threads Oldest First

Showing messages 1 through 1 of 1.

  • Runtime Exception is not informative
    2007-08-16 22:11:24  remotec [View]


    I believe the correct way to convert a checked exception into a runtime exception would be the following;

    }catch (ClassNotFoundException ce){
    throw new RuntimeException(ce);

    Note that we are passing the the checked exception into the runtime exception. This will generate the following stack trace.

    Exception in thread "main" java.lang.RuntimeException: java.lang.ClassNotFoundException: jdbc.odbc
    at ExceptionTest.main(ExceptionTest.java:25)
    Caused by: java.lang.ClassNotFoundException: jdbc.odbc
    at java.net.URLClassLoader.findClass(URLClassLoader.java:376)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:572)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:442)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
    at java.lang.Class.forName1(Native Method)
    at java.lang.Class.forName(Class.java:180)
    at ExceptionTest.main(ExceptionTest.java:23)