public class ConnectionManager {
private static String url = "jdbc:mysql://localhost:3306/prototypeeop";
private static String driverName = "com.mysql.jdbc.Driver";
private static String usernsme = "root";
private static String pasword = "triala";
private static Connection con;
private static String url;
public static Connection getConnection() {
try {
Class.forName(driverName);
try {
con = DriverManager.getConnection(url, username, password);
} catch (SQLException ex) {
// log an exception. fro example:
System.out.println("Failed to create the database connection.");
}
} catch (ClassNotFoundException ex) {
// log an exception. for example:
System.out.println("Driver not found.");
}
return con;
}
}
嘿,我正在制作这个类,我得到一个“classnotfound 异常永远不会在相应的 try 语句的主体中抛出”?这与我的 try 和 catch block 有关,我想知道问题出在哪里。对于 try 错误,它表示“未报告的异常 java.lang.classnotfound 异常必须在抛出之前捕获或声明”。
对于显而易见的问题,我深表歉意,但我也是新手,尝试捕捉障碍。我知道这与我没有声明此类错误有关,因为 SQLException 已在 java.sql 包中声明;因此,为什么我没有收到错误。 (我在我的代码中包含“导入 java.sql 包”,因为我正在使用 JDBC 的 Connection 类)。该类基本上建立了一个连接并返回该连接。
最佳答案
你的文字很难理解......如果我正确理解你的问题,这可能是答案:
您必须捕获 SQLException,因为 DriverManager.getConnection 声明它可能会抛出此异常。 Class.forName 可能会抛出 ClassNotFoundException,因此您也必须捕获它。但是,您可以将一个 try block 与两个 catch 子句一起使用,而不是两个。
我想最好的办法是你能重新解释这个问题。
关于java - 尝试捕捉错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10939060/