SoFunction
Updated on 2024-10-30

python exception handling of try finally does not report error reasons

Since there is a need to package a python program as an exe, the following code is available

import time

class LoopOver(Exception):
  def __init__(self, *args, **kwargs):
    pass

class Spider:
  def __init__(self):
    super().__init__()

  def run(self):
    raise LoopOver

  @property
  def time(self):
    return 'Total time spent:{}unit of angle or arc equivalent one sixtieth of a degree'.format()


if __name__ == '__main__':
  try:
    spider = Spider()
    ()
    print() # Total running time
  finally:
    print('Dead.')
    (60 * 60)

But there's a problem.

Programs that display "after death" do not display a stack error message.

Troubleshooting found that the program prints the "stack error message" is not asynchronous, the "stack error message" will wait until the execution of the code block within the finally will be output!

So, change the code block a little bit.
Need to import traceback library to trace stack error messages
as shown below

import time
import traceback


class LoopOver(Exception):
  def __init__(self, *args, **kwargs):
    pass


class Spider:
  def __init__(self):
    super().__init__()

  def run(self):
    raise LoopOver

  @property
  def time(self):
    return 'Total time spent:{}unit of angle or arc equivalent one sixtieth of a degree'.format()


if __name__ == '__main__':
  try:
    spider = Spider()
    ()
    print() # Total running time
  finally:
    traceback.print_exc()
    print('Dead.')
    (60 * 60)

This printing is asynchronous, I don't know if it's multithreaded or concurrent or what

For more on tracking stack error messages, check out this article
Several ways Python captures exception stack information

To this point this article on python exception handling try finally do not report the reason for the error of the article is introduced to this, more related python try finally do not report the error of the contents of the search for my previous articles or continue to browse the following related articles I hope that you will support me in the future more!