ClassNotFoundException

ClassNotFoundException is a checked exception from java.lang package, you get generally when you load a class manually with forName() method of class Class. This you experience in JDBC (Java Database Connectivity) where you load the driver from hard disk.

Observe the following snippet of code.

Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);

In the above statement, forName() method of class Class loads the JDBC driver by name JdbcOdbcDriver from the hard disk. sun.jdbc.odbc is the package structure where JdbcOdbcDriver class is available.

See the method signature of forName() method.

forName(String) throws ClassNotFoundException
(for brevity, return type is not included in the signature)

Observe, the forName() throws a checked exception ClassNotFoundException; being checked, it must be handled.

Following is the hierarchy.

Object –> Throwable –> Exception –> ClassNotFoundException

Full hierarchy of exceptions is available at "Hierarchy of Exceptions – Checked/Unchecked Exceptions".

As we are not writing any JDBC code, it is illustrated with our own class CNFE.

public class CNFE
{
  public static void main(String args[])
  {    
    try
    {
      Class.forName("Test");
    }
    catch(ClassNotFoundException e)
    {
       System.out.println("Sorry, class is not existing. " + e);
    }
  }
}

ClassNotFoundException

Demo class would like to load Test class. But infact, Test class is not available (does exist at all). JVM throws ClassNotFoundException. Observe the screenshot.

Note: Do not get confused. There is class called Class in Java from java.lang package. Like this there is file called File from java.io package. Other one is Object class.

Leave a Comment

Your email address will not be published.