【问题标题】:How to traceback the thrown error in python3.7?如何追溯python3.7中抛出的错误?
【发布时间】:2019-11-15 22:14:00
【问题描述】:

我有一个典型的场景,我有一个如下所示的模块:

def fun2():
   #does something which can throw a ValueError exception

def fun3():
   #does something which can throw a ValueError exception

def fun1:
   fun2() #call to fun2
   fun3() #call to fun3

def fun0:
   try:
       fun1()
   except ValueError as e: 
       ##try to find out from which function ValueError Exception is thrown 
       print(customErrorMsg)

如何发现fun0 的except 块中,fun2fun3 抛出了错误?我试过e.__traceback__,但它没有提供有用的输出。 严格来说,当从fun2fun3 抛出异常时,我想打印不同的customErrorMsg

【问题讨论】:

  • 你能展示一个你现在得到的完整回溯的例子吗?
  • 当我使用 e.__traceback__ 时,我得到
  • 我的意思是,如果您只是在 except ValueError as e: 声明中执行 print(e)
  • 一种方法是修改您的fun1 并分别尝试fun2()fun3() 这两个语句?

标签: python error-handling try-catch try-except


【解决方案1】:

你可以这样做

def fun1:
    try:
        fun2() #call to fun2
    except ValueError as e:
        print(error_message)
    try:
        fun3() #call to fun3
    except ValueError as e:
        print(error_message)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-07
    • 2017-07-05
    • 2023-03-14
    • 1970-01-01
    • 2017-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多