未报告的异常java.sql.SQLException;必须被抓住或宣布被扔出去?

未报告的异常java.sql.SQLException;必须被抓住或宣布被扔出去?,java,Java,我在编译下面的代码时遇到了这个错误。我想知道我做错了什么 unreported exception java.sql.SQLException; must be caught or declared to be thrown Class.forName(myDriver); ^ 您需要捕获方法中的异常: public void setupInfo() { try { // call methods that might throw

我在编译下面的代码时遇到了这个错误。我想知道我做错了什么

unreported exception java.sql.SQLException; must be caught or declared to be thrown Class.forName(myDriver); ^
您需要捕获方法中的异常:

public void setupInfo()
{
    try
    {
        // call methods that might throw SQLException
    }
    catch (SQLException e)
    {
        // do something appropriate with the exception, *at least*:
        e.printStackTrace();
    }
}
声明抛出
SQLException
的方法:

private void setupInfo() throws SQLException
{
    // call methods that might throw SQLException
}

这行代码引发未捕获的异常:

Driver driver = new org.gjt.mm.mysql.Driver();
试试这个:

try {
   Driver driver = new org.gjt.mm.mysql.Driver();
}
catch (java.sql.SQLException e) {
  // you may want to do something useful here
 // maybe even throw new RuntimException();
}

捕获或抛出异常。最好使用IDE(Eclipse或Netbeans),它会在您按enter键时告诉您错误。

始终尝试从IDE获得帮助。IDE通常可以自动修复错误。在IntelliJ IDEA中按alt+enter或在Eclipse中按ctrl+1,然后选择修复错误。

您正在阅读过时的MySQL JDBC教程/示例。MySQL在8年前就接管了这个项目,从那时起就被称为with
com.MySQL.jdbc.Driver
。MM驱动程序类名只是为了向后兼容而保留的,但实际上应该使用
com.mysql.jdbc.driver
。顺便说一下,您的编译错误与发布的源代码不匹配。您没有在源代码中的任何位置使用
Class#forName()
。更糟糕的是,它根本不会抛出
SQLException
。不幸的是(IMO)对这个错误的典型纠正是捕获异常,打印一个stacktrace到stderr,然后继续,就好像什么都没有发生一样。一般来说,这不是正确的做法。通常有两种选择——捕获或抛出。你能简单解释一下它们的作用吗?@AnubianNoob这是非常基本的Java。我知道它是如何工作的,但这会让答案更清楚。编辑:哦,我不知道这是从2010年开始的,对不起。。。
try {
   Driver driver = new org.gjt.mm.mysql.Driver();
}
catch (java.sql.SQLException e) {
  // you may want to do something useful here
 // maybe even throw new RuntimException();
}