Python exception handling

Python includes a bunch of built-in exception classes
and we can easily create our own by creating a class which derives from Exception.

For example, here’s a MethodNotImplementedException type

class MethodNotImplementedException(Exception):
    def __init__(self, *args, **kwargs):
        pass

    def __str__(self):
        return "Method not implemented"

In this example I’ve overridden the __str__
method to return a simple string when we print the exception to stdout.

We need not create specific exception types but obviously this allows us to also catch specific exception types.

Here’s an example of some code that raises (throws) an exception and the code to catch and handle an exception

class Animal:
    def name(self):
        raise MethodNotImplementedException()


a = Animal()
try:
    a.name()
except MethodNotImplementedException as e:
    print(e)
except Exception as e:
    raise
finally:
    print("finally called")

We create a try block and exceptions are caught using the except
statement. As can be seen we can catch and filter each exception type we want to handle and include a finally
block as required.

To rethrow and exception we simple call the raise
method.

My Memory稿源:My Memory (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 综合编程 » Python exception handling

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录