简体   繁体   English

为什么异常没有打印在except块中

[英]Why exception isn't printed in except block

I'm trying to assert a message from an except block, something like this:我正在尝试从一个 except 块中断言一条消息,如下所示:

assert exceptions.main() == f"Join into Exception: {exceptions.CustomException}"

I'm using these files:我正在使用这些文件:

# main file
class CustomException(Exception):
    """
    This is a custom exception
    """

def return_an_exception():
    pass

def another_func():
    pass

def main():
    try:
        return_an_exception()
        another_func()
    except CustomException as e:
        return f"Join into Exception: {str(e)}"
    return "Not join into Exception"
# test file
import exceptions


def test_exceptions(
    mocker,
):
    mocker.patch("exceptions.return_an_exception").side_effect = exceptions.CustomException 
    mocker.patch("exceptions.another_func")
    assert exceptions.main() == f"Join into Exception: {exceptions.CustomException}"

I'm getting this error:我收到此错误:

========================================================================================== FAILURES ==========================================================================================
______________________________________________________________________________________ test_exceptions _______________________________________________________________________________________

mocker = <pytest_mock.plugin.MockerFixture object at 0x102413f40>

    def test_exceptions(
        mocker,
    ):
        mocker.patch("exceptions.return_an_exception").side_effect = exceptions.CustomException
        mocker.patch("exceptions.another_func")
>       assert exceptions.main() == f"Join into Exception: {exceptions.CustomException}"
E       assert 'Join into Exception: ' == "Join into Ex...omException'>"
E         - Join into Exception: <class 'exceptions.CustomException'>
E         + Join into Exception:

test_exceptions.py:9: AssertionError
================================================================================== short test summary info ===================================================================================
FAILED test_exceptions.py::test_exceptions - assert 'Join on Exception: ' == "Join on Exce...omException'>"
===================================================================================== 1 failed in 0.06s ======================================================================================

Could you help me understand why e isn't printed你能帮我理解为什么不打印e

That's because the default implementation of the __str__ method of an Exception is to return its message:那是因为Exception__str__方法的默认实现是返回其消息:

print(Exception())                    # Prints nothing
print(Exception("An error occured"))  # Prints "An error occured"

You can fix this by printing e.__class__.__name__ instead:您可以通过打印e.__class__.__name__来解决此问题:

class CustomException(Exception):
    pass

def return_an_exception():
    raise CustomException

def another_func():
    pass

def main():
    try:
        return_an_exception()
        another_func()
    except CustomException as e:
        return f"Join into Exception: {e.__class__.__name__}"
    return "Not join into Exception"
    
print(main())  # Now prints "Join into Exception: CustomException"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM