我有一个下面定义的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块?
注意:我在这里没有提到完整的代码,因为我认为我的问题与代码无关。
最佳答案
像这样更改您的代码。快速跳过它的失败。
// 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
关于java - 迅速摆脱困境,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23067518/