简单 Python 快乐之旅之:Python 基础语法之异常处理专题

1. Python try 语句示例

Python 的 try 语句用于处理在运行时由 Python 解释器抛出的异常。当解释器抛出一个错误时,程序的执行会突然中止。要避免这种情况我们可以使用 try 语句对异常进行编程式的捕捉和处理。

1.1. Python 中 try 语句的语法

try:
	#your code that may throw exceptions
	statement(s)
except Exception1:
	#If Exception1 is thrown, then execute this block.
	statement(s)
except Exception2:
	#If Exception2 is thrown, then execute this block.
	statement(s)
else:
	#If there is no exception then execute this block. 
	statement(s)

将你可能抛异常的代码包含于 try 语句块中,然后跟随于 except 语句块。你可以处理 try 语句块中的代码所抛出的多种异常。假如你的 try 语句块中的代码能够抛出两种类型的异常,我们可以使用两个 except 语句块对两种异常进行分别处理。你可以为可能发生的每一种异常类型分别提供后续的执行语句块。
else 语句块是可选的。如果你提供了 else 语句块,它只会在 try 语句块没有抛出任何异常的时候执行。

1.2. try 语句块的示例

本示例中,我们进行一个两数相除的运算。当被除数为零的时候 Python 解释器将会抛出一个异常,我们使用 except 语句块对其进行捕捉。

# Example for Python Try Catch
a = 3
b = 0
c = 0
try:
    c = a / b
except ZeroDivisionError:
    print("b is zero. Correct the value or your logic.")
print(c)

执行和输出:
try 语句块的示例.png
如果我们不使用 try 语句块会发生什么呢?
如果我们不使用 try 语句块会发生什么呢.png

2. TypeError: method() takes 0 positional arguments but 1 was given

这种错误说的是,根据该方法的定义,它不接受任何参数,但是我们却传给它一个参数。
以下示例演示了如何重现这种错误:

# TypeError: method() takes 0 positional arguments but 1 was given
class Laptop:
    def details():
        print("Hello! I am a laptop")
laptop1 = Laptop()
laptop1.details()

执行和输出:
不接受任何参数,但是我们却传给它一个参数.png
你可能会有疑问,在调用 laptop1 对象的 details() 方法的时候明明没有传给它任何参数呀,但怎么就抛出了这种 TypeError 呢?
在默认情况下,如果方法不是一个静态的 Python 方法,会隐式地将对象 (self) 作为参数传递给它。因此,在你调用 laptop1.details() 的时候,实际上被调用的是为 laptop1.details(laptop1)。因此为了遵守这一内在行为,我们需要在定义 details() 方法的时候就传给它一个参数:

# Provide an argument in the definition of details() method
class Laptop:
    def details(self):
        print("Hello! I am a laptop")
laptop1 = Laptop()
laptop1.details()

执行和输出:
在定义 details() 方法的时候就传给它一个参数.png
当然,还有一个办法,就是将其定义为一个静态方法。你可以使用注解 @staticmethod 告诉 Python 解释器说明这是一个静态方法:

# Tell Python Interpreter that this method is a static method
class Laptop:
    @staticmethod
    def details():
        print("Hello! I am a laptop")
laptop1 = Laptop()
laptop1.details()

执行和输出:
将其定义为一个静态方法.png

参考资料

发布了273 篇原创文章 · 获赞 1324 · 访问量 649万+

猜你喜欢

转载自blog.csdn.net/defonds/article/details/100485491
今日推荐