Java 验证串口监听器是否已经添加

Java verify if serial port listener is added already

如何验证Java中是否已经添加了串口监听,使".removeEventListener()"不会产生异常:

jssc.SerialPortException: Port name - COM4; Method name - removeEventListener(); Exception type - Can't remove event listener, because listener not added.

感谢您的帮助

正如@Jordi Castilla 所提到的,最好的办法是捕获异常。如果您想确保异常发生是因为未添加侦听器,请检查异常类型:

try {
    port.removeEventListener()
} catch (SerialPortException e) {
    if (e.getExceptionType().equals(SerialPortException.TYPE_CANT_REMOVE_LISTENER)) {
        // the listener hasn't been added
    } else {
        // other exceptions
    }
}