2015-02-23 122 views
1

这是我尝试使用jdk进行编译的程序。在程序中的“satya”引用msaccess数据库文件的数据库。当我尝试编译它显示错误时"MyClass.java:0:error:unreported exception ClassNotFoundException;must be caught or declared to be thrown"。即使我将程序中的异常从SQLException更改为异常,它也可以成功编译。但运行程序时抛出异常。如何执行?未报告的异常ClassNotFoundException;必须被捕获或声明为抛出

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>"); 
      } 
} 
} 

回答

0

你的方法之一会抛出一个ClassNotFoundException,你有责任处理这些例外。 在这种情况下,异常OT打印到控制台了一个quickfix

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

(请拓展与输出你的问题)。

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

0

ClassNotFoundException是Exception的子类,这就是为什么你通过编译器。 SQLException类不包装ClassNotFoundException。由于“Class”类的forName()方法声明为“throws ClassNotFoundException”,编译器将要求您使用调用方法的try/catch块或throws子句包装方法调用。 catch块必须使用ClassNotFoundException或其一个父类Exception类。

您需要找出在运行时抛出的异常,以检查它未能提前运行的原因。

相关问题