快速走出捕获区块

时间:2014-04-14 18:29:10

标签: java jdbc

我有一个如下定义的try-catch块和一个for-each循环。

try
{

 // Doing some JDBC Connections here

  Map<String,Connection> connections = new HashMap<>();

   while(DeviceRS.next()){
   final String ip_address = DeviceRS.getString("Connection_vch");
       System.out.println("Value of the IP Address Field:"+ip_address);
   connections.put(ip_address,DriverManager.getConnection("jdbc:mysql://" + ip_address + ":3306/test",RemoteUser,RemotePass));
   }    

    for(final String ip : connections.keySet())
    {

      // Selecting and inserting into database here ...

     }// ENd of for loop

}// ENd of try block
catch(SQLException ex){

ex.printStackTrace();

}

因此,如果连接出现问题,我的程序将卡在catch块中,打印堆栈跟踪。我想转移到其他连接。

有没有办法可以在打印堆栈跟踪后快速退出catch块?

注意:我没有在此提及完整代码,因为我认为我的问题与我的代码无关。

3 个答案:

答案 0 :(得分:1)

像这样更改了你的代码。快速跳过它失败。

 // Doing some JDBC Connections here





       Map<String,Connection> connections = new HashMap<>();
        try
        {

           while(DeviceRS.next()){
           try{
           final String ip_address = DeviceRS.getString("Connection_vch");
           connections.put(ip_address,DriverManager.getConnection("jdbc:mysql://" + ip_address + ":3306/test",RemoteUser,RemotePass));
            }
            catch(SQLException ex){
            ex.printStackTrace();

             }
           }  
    catch(Exception ex){

        ex.printStackTrace();
            System.out.println("in catch block");
//System.exit(0); // dont use this -in real time projects
        }finally{
       System.out.println("in finally block");

        } 

            for(final String ip : connections.keySet())
            {

              // Selecting and inserting into database here ...

             }// ENd of for loop

        }// ENd of try block

答案 1 :(得分:0)

我认为没有好看的方式。但是你可以在try-catch中创建另一个try-catch块

 try {
     // your code here

     for(final String ip : connections.keySet()) {
         try { // inner catch
             // your code, that will be continued if sql exception occurs
         } catch (SQLException e) {
             e.printStackTrace();
         }
     }

 } catch (SQLException e) {
     e.printStackTrace();
 }

答案 2 :(得分:0)

就像你说的,如果你想要连接出现问题并想要转移到另一个连接上,那就这样做:

 boolean check = true;

 while(check) {
   try {

   Map<String,Connection> connections = new HashMap<>();

   while(DeviceRS.next()){

   final String ip_address = DeviceRS.getString("Connection_vch");
   connections.put(ip_address,DriverManager.getConnection("jdbc:mysql://" + ip_address   +    ":3306/test",RemoteUser,RemotePass));

  } // Ends inner while    

  check = false;  //As connection is ok,we don't need to loop back.  

   for(final String ip : connections.keySet())
   {

     // Selecting and inserting into database here ...
   }

 }// Ends try block

 catch(SQLException ex){

    ex.printStackTrace();

   } //Ends catch block

  finally{

         // close the connection if needed.
   } // Ends finally block

}// Ends outer while loop