请考虑以下代码:

代码段#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)

}


要么

代码片段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;
}


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

对于下一个问题:

因此,我知道如果必须使用异常对象显示某些内容,则可以在catch块内执行以下操作:

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


但是,就我而言,我正在使用catch块内的现有打开连接,如上所示,我想知道:

队列2)捕获异常后,catch块中的代码是否将自动开始执行?我很困惑,因为在我的System.out.println语句中,我正在使用ex对象来
显示所有消息,并且在该对象之后的JDBC连接中的任何地方都没有使用该对象。

队列3如果在末尾使用break语句并退出catch块,可以吗?由于break用于循环,我相信控制会自动从原始catch块出来吗?

队列1的澄清:

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

由于我在catch块中添加了额外的try-catch块,因此我想知道这种方法
好继续吗?只是想知道既然我在这里有更多的错误处理代码,所以这种方法应该比本文中介绍的方法更好。
代码片段1?

最佳答案

他们俩都不做你想要的。我什至不知道你想要什么。
是。一旦try块中的内容引发异常,执行将直接进入catch块并退出try块。 ex对象本身就是异常,并且由引发该异常的任何代码生成。
否。如果您正在考虑的话,就没有办法回到引发异常之后。在catch块中的最后一条语句之后,执行转到catch块之后的下一条语句(其他catch块除外)。


3a。 break用于循环和switch块。脱离catch块就像脱离if语句。

但我认为您不理解例外。如果出现问题,将引发异常-它在建立连接中不起作用。如果DriverManager.getConnection抛出SQLException,则当它尝试连接到数据库时出了点问题,因此它没有连接到数据库。如果仍然尝试使用数据库连接,那将是失败的秘诀。如果确实发生了,除了显示错误消息并放弃之外,您无能为力。

10-02 11:06