[Python] Raise an error in file B that takes me back to specific point in file A in python

Discussão em 'Python' iniciado por Stack, Abril 2, 2025.

  1. Stack

    Stack Membro Participativo

    I have a question. I am running a python project with multiple files with multiple classes. Let's say in file A, I am running a process in a try-exception. In this try-exception a function is called from a different file B/class.

    The function in file B is quite complicated as there a a couple while/ and try-exceptions statements. However, within the most inside function, I am putting a counter and if this counter reaches a certain amount, I want it to raise an error that takes me back to the try-exception / to a specific point in file A. The problem that I now have is that the error that I am raising doesn't abort the function in file/class B so it would take me to file/class A, but it takes me to the with.media.getSynchronous statement that is outside of the try-exception, see code below:

    with self.media.getSynchronous():
    if not reply.isStreaming():
    self.writeTrace("TX: " + self.now() + "\t" + GXByteBuffer.hex(data), TraceLevel.VERBOSE)
    self.media.send(data)
    pos = 0
    try:
    while not self.client.getData(rd, reply, notify):
    if notify.data.size != 0:
    if not notify.isMoreData():
    t = GXDLMSTranslator()
    xml = t.dataToXml(notify.data)
    print(xml)
    notify.clear()
    continue
    if not p.eop:
    p.count = self.client.getFrameSize(rd)
    while not self.media.receive(p):
    pos += 1
    if pos == 4:
    raise TimeoutException("Failed to receive reply from the device in given time.")
    if pos == 1:
    self.counter+= 1
    if self.counter>= 2:
    logging.warning(f"Worker {self.worker_id} | counteris {self.counter}")
    raise STOP(f"Data send failed, limit reached ({self.counter})")
    logging.info(f"Worker {self.worker_id} | Meter ({self.meternummer}) - Data send failed. Try to resend " + str(pos) + f"/3, times: {self.counter}")
    self.media.send(data, None)
    rd.set(p.reply)
    p.reply = None
    except Exception as e:
    self.writeTrace("RX: " + self.now() + "\t" + str(rd), TraceLevel.ERROR)
    raise e
    self.writeTrace("RX: " + self.now() + "\t" + str(rd), TraceLevel.VERBOSE)
    if reply.error != 0:
    raise GXDLMSException(reply.error)


    Is there a way that I call an exception or return so that I go back to file A, because now the script gets stuck in file B

    Continue reading...

Compartilhe esta Página