如何在Python 3中打印异常? [英] How to print an exception in Python 3?

查看:414
本文介绍了如何在Python 3中打印异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,我在例外:子句中捕获到该例外,并执行 print(exception)。由于该结果始终会打印<类 Exception> ,因此该结果不提供任何信息。我知道这曾经在python 2中起作用,但是我如何在python3中做到这一点?

解决方案

我猜你需要将 Exception 分配给变量。如在Python 3教程中所示

b
$ b

  def fail():
x = 1/0

try:
fail()
除外,例如ex:
print(ex)

as 是在某些复合语句中使用的伪分配关键字,用于将前面的语句分配或别名给变量。



在这种情况下, as 将捕获的异常分配给变量,以允许有关异常的信息在以后存储和使用,而无需立即进行处理。 (这在 Python 3语言参考中进行了详细讨论: code> try 语句。)






其他复合语句使用 as with 语句:

  @contextmanager 
def开头(文件名):
f =打开(文件名)
试试:
最终收益f

f.close()

,其中开头(文件名)为f:
#...从f ...


在这里,带有$code>的语句用于使用上下文管理器。该函数的功能类似于扩展的 try ...,除了...最终整齐的生成器包中的语句,以及 as 语句将上下文管理器中生成器产生的结果分配给变量以供扩展使用。
(这在 Python 3语言中进行了详细讨论参考: with 语句。)






最后,在导入模块时可以使用 as 作为模块的别名,以使用不同的名称(通常较短):

 将foo.bar.baz导入为fbb 

有关详细信息,请参见 Python 3语言参考:导入声明


Right now, I catch the exception in the except Exception: clause, and do print(exception). The result provides no information since it always prints <class 'Exception'>. I knew this used to work in python 2, but how do I do it in python3?

解决方案

I'm guessing that you need to assign the Exception to a variable. As shown in the Python 3 tutorial:

def fails():
    x = 1 / 0

try:
    fails()
except Exception as ex:
    print(ex)

To give a brief explanation, as is a pseudo-assignment keyword used in certain compound statements to assign or alias the preceding statement to a variable.

In this case, as assigns the caught exception to a variable allowing for information about the exception to stored and used later, instead of needing to be dealt with immediately. (This is discussed in detail in the Python 3 Language Reference: The try Statement.)


The other compound statement using as is the with statement:

@contextmanager
def opening(filename):
    f = open(filename)
    try:
        yield f
    finally:
        f.close()

with opening(filename) as f:
    # ...read data from f...

Here, with statements are used to wrap the execution of a block with methods defined by context managers. This functions like an extended try...except...finally statement in a neat generator package, and the as statement assigns the generator-produced result from the context manager to a variable for extended use. (This is discussed in detail in the Python 3 Language Reference: The with Statement.)


Finally, as can be used when importing modules, to alias a module to a different (usually shorter) name:

import foo.bar.baz as fbb

This is discussed in detail in the Python 3 Language Reference: The import Statement.

这篇关于如何在Python 3中打印异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆