未报告的异常ClassNotFoundException;必须被捕获或声明为抛出

时间:2015-02-23 12:22:41

标签: java

这是我尝试使用jdk编译的程序。程序中的“satya”是指一个msaccess db文件数据库。当我尝试编译时,它显示的错误如"MyClass.java:0:error:unreported exception ClassNotFoundException;must be caught or declared to be thrown"。即使我更改了异常在程序从SQLException到Exception它编译成功。但是在运行程序时抛出异常。如何执行?

import java.sql.*;

class MyClass
{
     public static void main(String args[])
     {

      try{ 
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
           Connection con=DriverManager.getConnection("jdbc:odbc:satya","","");
           Statement st=con.createStatement();
           ResultSet rs=st.executeQuery("select * from studentinfo");
           while(rs.next())
           {
             System.out.println(rs.getInt(1)+"\t"+
             rs.getString(2)+"\t"+
             rs.getString(3)+"\t");
           }
         rs.close();
        st.close();

        }
        catch (SQLException e) {
             System.out.println("<P>" + "There was an error doing the query:");
            System.out.println ("<PRE>" + e + "</PRE> \n <P>");
          }
 }
 }

2 个答案:

答案 0 :(得分:0)

你的一个方法抛出一个ClassNotFoundException,你有责任处理这些异常。 一个quickfix

public static void main(String args[]) throws Exception

在这种情况下,异常会打印到您的控制台(请使用该输出扩展您的问题)。

此外,请确保将jdbc驱动程序库添加到项目中。

答案 1 :(得分:0)

ClassNotFoundException是Exception的子类,这就是你传递编译器的原因。 SQLException类不会包装ClassNotFoundException。由于“forName()”类的Class方法声明为“throws ClassNotFoundException”,编译器将要求您使用try / catch块或{{1来包装方法调用调用方法的子句。 throws块必须使用catch或其中一个父ClassNotFoundException类。

您需要弄清楚在运行时抛出的异常,以检查它无法提前运行的原因。