SQL Exception对象在catch块内建立连接的作用

时间:2014-03-11 04:08:31

标签: java jdbc

请考虑以下代码:

代码段#1

Statement InsertRemoteResultsStmt = null;
Connection connRemote = null;
try {
     connRemote = DriverManager.getConnection("//my urls here");

     // other stuff here
}

catch(SQLException ex)

{

     System.out.println("SQLException: " + ex.getMessage());
     System.out.println("SQLState: " + ex.getSQLState());
     System.out.println("VendorError: " + ex.getErrorCode());

    // For Connection #1 
    InsertRemoteResultsStmt = connRemote.createStatement(); 
    // Rest of the connection code

    // For Connection #2 (Will be a new connection) 

}

OR

代码段#2:

Statement InsertRemoteResultsStmt = null;
Connection connRemote = null;
try {
     connRemote = DriverManager.getConnection("//my urls here");

     // other stuff here
}

catch(SQLException ex) // Original catch block

{

     System.out.println("SQLException: " + ex.getMessage());
     System.out.println("SQLState: " + ex.getSQLState());
     System.out.println("VendorError: " + ex.getErrorCode());

     try{

    // For Connection #1 ( Will be using an existing one)
    InsertRemoteResultsStmt = connRemote.createStatement(); 
    // Rest of the connection code

    // For Connection #2 (Will be a new connection) 
         }

    Catch(SQLException insidecatch)
    {

     }  

     break;
}

Que#1 在我的案例中,代码片段#2是处理异常的更好方法吗?

下一个问题:

所以,我明白如果我必须使用异常对象显示一些内容,我可以在catch块中执行类似的操作:

System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());

但是,在我的情况下,我正在使用catch块内的现有已打开的连接,如上所示,我想知道:

Que#2)一旦发现异常,catch块内的代码是否会自动开始执行?我很困惑,因为在我的System.out.println语句中,我使用的是ex个对象 显示所有消息,我没有在它后面的JDBC连接中的任何地方使用此对象。

Que#3 如果我在最后使用break语句并退出catch块,这样可以吗?由于break用于循环,我相信控件会自动从原始catch块中出来吗?

对Que#1的澄清:

我基本上比较了两种保持错误处理的方法,我计划使用的方法之一。 在Code Snippet#1中,我没有在catch块中添加任何额外的try-catch块,反之亦然 代码片段#2。我基本上在catch块中使用两个连接。 Connection#1将是一个将用于的连接 在一个数据库中插入一些记录,在Connection#2中插入相同的记录。

由于我在catch块中添加了额外的try-catch块,我想知道这种方法 好继续吗?只是想知道,因为我在这里有更多的错误处理代码,这种方法应该比提出的方法更好 代码片段#1?

1 个答案:

答案 0 :(得分:4)

  1. 他们都没有做你想做的事。我甚至不确定你想要什么。

  2. 是。一旦从try块内的某个东西抛出异常,执行将直接进入catch块并退出try块ex对象本身就是异常,并且由抛出异常的任何代码生成。

  3. 没有。如果这就是你所想的那样,就没有办法在抛出异常之后再回过头来。在catch块中的最后一个语句之后,执行将转到catch块之后的下一个语句(其他catch块除外)。

  4. 3A。 break用于循环和switch块。打破一个catch块就像打破if语句一样。

    但我不认为你理解异常。如果出现问题,则抛出异常 - 它在建立连接时不起作用。如果DriverManager.getConnection抛出SQLException,那么当它尝试连接到数据库时会出现问题,因此它没有连接到数据库。如果您尝试使用数据库连接,那就是失败的秘诀。如果确实发生了这种情况,除了显示错误消息和放弃之外,你可以做的事情并不多。