How to print an exception in Python 3?

前端 未结 7 2225
有刺的猬
有刺的猬 2021-01-31 13:48

Right now, I catch the exception in the except Exception: clause, and do print(exception). The result provides no information since it always prints

7条回答
  •  爱一瞬间的悲伤
    2021-01-31 14:34

    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.

提交回复
热议问题