gpt4 book ai didi

python - 使用 try except 时递归打印异常详细信息

转载 作者:太空宇宙 更新时间:2023-11-03 15:12:10 25 4
gpt4 key购买 nike

#!/usr/bin/env python

#import re


def test_ex1(input):
if re.match(r'^[A-Z]+$',input):
print 'Match'
return True
print 'No Match'
return False


#test_ex1('ABC')
try:
test_ex1('ABC')
except Exception:
raise Exception

如果我运行上面的程序,它将打印以下异常消息。

a:~/Python> python test.py
Traceback (most recent call last):
File "test.py", line 18, in <module>
raise Exception
Exception

Python 中使用 try except 捕获异常时打印以下堆栈跟踪的正确方法是什么?不改变test_ex1子程序?

Traceback (most recent call last):
File "test.py", line 15, in <module>
test_ex1('ABC')
File "test.py", line 8, in test_ex1
if re.match(r'^[A-Z]+$',input):
NameError: global name 're' is not defined

最佳答案

一种方法是使用traceback模块

import traceback

try:
re.match()
except Exception:
traceback.print_exc()

关于python - 使用 try except 时递归打印异常详细信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44139348/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com