'This time-out error ('TimeOutError') is not being caught

I cannot understand why sometimes I cannot catch the TimeOutError inside my flash_serial_buffer method.

When running my program I sometimes get a TimeOutError that is not caught and I cannot understand why. I indicate the code of the signal handlers and the methods where the TimeOutError is not caught. How could this be happening?

This is the code for my signal handler definition and callback function.

Basically if the time ends, the signal handler is called and raises a timeout error.

def signal_handler(signum, frame):
    print "PUM"
    raise TimedOutError("Time out Error")

signal.signal(signal.SIGALRM, signal_handler)

The flush serial buffer blocks if there is no answer to

answer = xbee.wait_read_frame()

The idea is to clean everything in the buffer until there aren’t any more messages. When there are no more messages, it just waits for the SIGALRM to explode and raises the timeout error.

def flush_serial_buffer(xbee):

    # Flush coordinators serial buffer if problem happened before
    logging.info("     Flashing serial buffer")
    try:
        signal.alarm(1)  # Seconds
        while True:
            answer = xbee.wait_read_frame()
            signal.alarm(1)
            logging.error("    Mixed messages in buffer")
    except TimedOutError:
        signal.alarm(0)  # Seconds
        logging.error("    No more messages in buffer")

    signal.alarm(0) # Supposedly it never leaves without using Except, but...

Is there a case where the TimeOutError might be raised, but not caught by the try: statement?

Here is my error class definition:

class TimedOutError(Exception):
pass

I was able to repeat the error again. I really cannot understand why the try does not catch the error it.

INFO:root:     Flashing serial buffer
PUM
Traceback (most recent call last):
  File "/home/ls/bin/pycharm-community-4.0.6/helpers/pydev/pydevd.py", line 1458, in trace_dispatch
    if self._finishDebuggingSession and not self._terminationEventSent:
  File "/home/ls/PiProjects/Deployeth/HW-RPI-API/devices.py", line 42, in signal_handler
    raise TimedOutError("Time out Error")
TimedOutError: Time out Error


Solution 1:[1]

I would recommend in this case replacing the try and except code with this:

try:
    signal.alarm(1)  # Seconds
    while True:
        answer = xbee.wait_read_frame()
        signal.alarm(1)
        logging.error("    Mixed messages in buffer")
except:
    signal.alarm(0)  # Seconds
    logging.error("    No more messages in buffer")

PS: You don't need to include try (whatever error) in your try and except statements.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Peter Mortensen