简体   繁体   中英

Exception in try-catch-block is not caught in Java

I am quite new to Java and stumbled upon an problem, I can't understand (I am using Eclipse Luna for developing and executing):

I call a method that might throw an error and surrounded it with a try-catch-block:

try {
  transaction.execute();                
} catch (ModbusIOException e) {
  log.debug("Fehler bei Modbustransaction: ModbusIOException - " + e.getMessage());
  e.printStackTrace();
} ... // more catches

The execute-method actually throws the ModbusIOException - but it is not caught in the catch-block. In the console I got the following output:

net.wimpi.modbus.ModbusIOException: Read failed at net.wimpi.modbus.io.ModbusTCPTransport.readResponse(ModbusTCPTransport.java:180) at net.wimpi.modbus.io.ModbusTCPTransaction.execute(ModbusTCPTransaction.java:193) at de.vksys.modbusclient.ModbusClient.getPlantState(ModbusClient.java:121) at de.vksys.modbusclient.ReconnectingModbusClient.main(ReconnectingModbusClient.java:36)

If I click at the line with getPlantState Eclipse marks the line in the try-block above. But why isn't it caught there? I also checked the full name of the ModbusIOException in the catch block and is the same ... net.wimpi.modbus.ModbusIOException.

Any idea, what might be the reason? If you need more code to track this down, just tell me.

Thanks in advance,
Frank

It indeed caught the exception. You just printed the stack trace and that's what you see in the standard output.

Catching an exception, doesn't mean that it wont maintain the stack trace and handling exception means that you need to code it so you could recover from the exception (which is what has happened in your case else your program would have went to the parent method which called your method rolling back the stack ie in readResponse method) where you might say ok things happen or you rethrow the exception. for eg given a code as below:

void myMethod() {
    try {
         methodThatThrowsIOException();
    } catch (IOException ioe) {
         ioe.printStackTrace();
    }
    System.out.println("I will be printed");

If you didn't caught the exception, then you would never have executed print statement like "I will be printed" }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM