mariadb 错误信息:java.sql.SQLException;必须被捕获或声明为抛出[重复]

zi8p0yeb  于 2023-04-20  发布在  Java
关注(0)|答案(1)|浏览(240)

此问题已在此处有答案

Unreported exception java.lang.Exception; must be caught or declared to be thrown [duplicate](3个答案)
4天前关闭。
所以我声明了一个SQL连接,如下所示:

public class db {

public void run() throws SQLException {
    try {
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/project", "rizkiaswangga", "");
    } catch (SQLException e) {
        System.out.println(e.getMessage());
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

}
我只是试图首先将MariaDB连接到我的Java项目,但是尽管我已经声明了SQLException,我仍然遇到如下错误消息:

Exception in thread "AWT-EventQueue-0" java.lang.RuntimeException: Uncompilable code - unreported exception java.sql.SQLException; must be caught or declared to be thrown

当我试图从其他类运行:

public class Start extends javax.swing.JFrame {

/**
 * Creates new form Start
 */
public Start() {
    initComponents();
    db myDb = new db();
    myDb.run();
}

我的代码有什么问题?任何帮助都将不胜感激:)

bhmjp9jg

bhmjp9jg1#

在run方法中,你声明了throws SQLException,但没有抛出异常。同样在Start方法中,你没有添加throws SQLException
public void run()方法中删除throw SQLException

public class db {

    public void run() {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/project", "rizkiaswangga", "");
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

}

相关问题