[英]How to create Python exception without stack trace?
I would like to create a Python exception that does not print the stack trace (for simple user errors).我想创建一个不打印堆栈跟踪的 Python 异常(用于简单的用户错误)。 I have created a function below that wraps a custom class, but I would prefer to bake it into the custom exception class directly, would that be possible somehow?我在下面创建了一个 function,它包装了一个自定义 class,但我更愿意将它直接烘焙到自定义异常 class 中,这可能吗?
class UserError(Exception):
pass
def throw_user_error(s_msg):
sys.tracebacklimit = 0
raise UserError(s_msg)
sys.tracebacklimit = 1000
To achieve that, you should create custom handler, not the exception.为此,您应该创建自定义处理程序,而不是异常。 And this handler even already exists in the standard library: For example:这个处理程序甚至已经存在于标准库中:例如:
class CustomException(Exception):
pass
from contextlib import suppress
def main():
with suppress(CustomException):
# throw this error without consequences
raise CustomException()
print('This won\'t be reached')
print('Exiting normally anyway')
main()
Exiting normally anyway
And one more effective way to hide traceback is to replace it:隐藏回溯的一种更有效的方法是替换它:
In [30]: def fn(n=0):
...: if n <= 0:
...: raise Exception
...: return fn(n-1)
...:
...: try:
...: fn(10)
...: except Exception as e:
...: raise e.with_traceback(None)
---------------------------------------------------------------------------
Exception Traceback (most recent call last)
<ipython-input-30-bc3c4e86e3cc> in <module>
7 fn(10)
8 except Exception as e:
----> 9 raise e.with_traceback(None)
Exception:
Without this line (believe me or not) if we propagate the exception further, we'll see the long-long stack of recursive calls.如果没有这条线(信不信由你),如果我们进一步传播异常,我们将看到长长的递归调用堆栈。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.