欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python的异常处理

程序员文章站 2024-01-25 22:15:22
...

异常处理

1.异常
Python使用异常对象来表示异常状态,并在遇到错误时引发异常。异常对象未被处(或捕获)时,程序将终止并显示一条错误消息(traceback)。如下。

>>> 1 / 0
Traceback (most recent call last):
 File "<stdin>", line 1, in ?
ZeroDivisionError: integer division or modulo by zero 

每个异常都是某个类(这里是ZeroDivisionError)的实例。你能以各种方式引发和捕获这些实例,从而逮住错误并采取措施,而不是放任整个程序失败。
2.raise语句,异常类
使用raise语句,并将一个类(必须是Exception的子类)或实例作为参数,能够引发异常

>>> raise Exception 
Traceback (most recent call last):
 File "<stdin>", line 1, in ?
Exception
>>> raise Exception('hyperdrive overload')
Traceback (most recent call last):
 File "<stdin>", line 1, in ?
Exception: hyperdrive overload 

python的异常处理
3.捕获异常
举一个异常的例子

x = int(input('Enter the first number: '))
y = int(input('Enter the second number: '))
print(x / y) 
Enter the first number: 10
Enter the second number: 0
Traceback (most recent call last):
 File "exceptions.py", line 3, in ?
 print(x / y)
ZeroDivisionError: integer division or modulo by zero 

我们能够捕获异常并对异常更加人性化的进行处理

try:
 x = int(input('Enter the first number: '))
 y = int(input('Enter the second number: '))
 print(x / y)
except ZeroDivisionError:
 print("The second number can't be zero!")

多个except
因为程序会遇到不同的报错

try:
  x = int(input('Enter the first number: '))
  y = int(input('Enter the second number: '))
  print(x / y)
except ZeroDivisionError:
 print("The second number can't be zero!")
except ValueError:
 print("That wasn't a number, was it?")

python的异常处理
使用else子句进行循环

while True:
 try:
 x = int(input('Enter the first number: '))
 y = int(input('Enter the second number: '))
 value = x / y
 print('x / y is', value)
 except:
 print('Invalid input. Please try again.')
 else:
 break 

运行结果
只要出现错误,程序就会要求用户提供新的输入。

Enter the first number: 1
Enter the second number: 0
Invalid input. Please try again.
Enter the first number: 'foo'
Enter the second number: 'bar'
Invalid input. Please try again.
Enter the first number: baz
Invalid input. Please try again.
Enter the first number: 10
Enter the second number: 2
x / y is 5