这是因为你没有捕获(catch)这类错误,却要抛出(thrown)这类错误所造成的,我上次只是告诉你要抛出系统捕获的错误告诉你要添加throw new SQLException(e.toString())一句而没有告诉你要改上面的catch,呵呵。解决办法有两种: throw new SQLException(e.toString()); 改为 throw new Exception(e.toString());或者catch (Exception e) 改为catch(SQLException e)
把下面的语句去掉: throw new SQLException(e.toString());
叶三耿,我把catch (Exception e)改为catch(SQLException e),错误变为: Connect.java:50:error:Exception "java.sql.InstantiationException" is not catched and does not appear in throws list [JLS 8.4.4] 我看见一些代码例子中的下面这句: Class.forName("com.mysql.jdbc.Driver").newInstance(); 没有“.newInstance()”,是不是这里有问题?不过有的例子又有,什么原 因呢?
咱们先不管那么多,你先采用我上面告诉你的第一种改法,看看系统说什么,也就是catch 和throw 部分改为如下: catch (Exception e) { // System.err.println ("Cannot connect to database server"); throw new Exception(e.toString()); }系统反馈什么你再告诉我。
叶三耿,我改了,呵呵(苦笑),错误变为: Connect.java:58:error:Exception "java.lang.Exception" is not catched and does not appear in throws list [JLS 8.4.4] 正是琢磨不定,是不是还要import什么???
又没有搞错?方法头都没有抛出异常,方法中竟然能够抛出? public static void main (String[] args) ... catch (Exception e) { // System.err.println ("Cannot connect to database server"); throw new Exception(e.toString()); } ... 如果想跑出,至少在方法头中作如下处理: public static void main (String[] args) throws Exception{ ...
throw new SQLException(e.toString());
改为
throw new Exception(e.toString());或者catch (Exception e)
改为catch(SQLException e)
throw new SQLException(e.toString());
Connect.java:50:error:Exception "java.sql.InstantiationException"
is not catched and does not appear in throws list [JLS 8.4.4]
我看见一些代码例子中的下面这句:
Class.forName("com.mysql.jdbc.Driver").newInstance();
没有“.newInstance()”,是不是这里有问题?不过有的例子又有,什么原
因呢?
的com.mysql.jdbc.Driver改为"mm.。"就好像可以了。
难道mysql太老?
{
// System.err.println ("Cannot connect to database server");
throw new Exception(e.toString());
}系统反馈什么你再告诉我。
Connect.java:58:error:Exception "java.lang.Exception"
is not catched and does not appear in throws list [JLS 8.4.4]
正是琢磨不定,是不是还要import什么???
public static void main (String[] args)
...
catch (Exception e)
{
// System.err.println ("Cannot connect to database server");
throw new Exception(e.toString());
}
...
如果想跑出,至少在方法头中作如下处理:
public static void main (String[] args) throws Exception{
...
(我用的org.gjt.mm.mysql.Driver与你的驱动程序不一样,不过我已经试通了!)
import java.lang.*;
import java.sql.*;public class Connect
{
public static void main (String[] args)
{
Connection conn = null; try
{
String userName = "root";
String password = "";
String url = "jdbc:mysql://localhost/tryjava";
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection (url, userName, password);
System.out.println ("Database connection established");
}
catch (Exception e)//这样测试把一切错误都捕捉并进行处理了
{
System.err.println ("Cannot connect to database server");
}
finally
{
if (conn != null)
{
try
{
conn.close ();
System.out.println ("Database connection terminated");
}
catch (Exception e) { /* ignore close errors */ }
}
}
}
}