python try catch语句示例
时间: 2023-07-17 19:56:16 浏览: 102
当Python程序运行时,可能会出现错误。为了避免程序崩溃,Python提供了try/except语句,可以捕获并处理异常。以下是一个简单的try/except语句的示例:
```python
try:
x = 5 / 0
except ZeroDivisionError:
print("除数不能为零!")
```
在这个示例中,我们试图将5除以0,这是不允许的,会引发ZeroDivisionError异常。由于我们使用了try/except语句,因此程序不会崩溃,而是打印出了异常信息:"除数不能为零!"。
您还可以使用多个except子句来捕获不同类型的异常,并根据不同的异常类型做出不同的处理。例如:
```python
try:
f = open("file.txt")
s = f.readline()
i = int(s.strip())
except IOError:
print("无法打开文件!")
except ValueError:
print("无法将字符串转换为整数!")
except:
print("未知错误!")
finally:
f.close()
```
在这个示例中,我们打开一个名为"file.txt"的文件,并尝试读取第一行并将其转换为整数。如果文件无法打开,我们将打印出"无法打开文件!"的错误信息;如果无法将字符串转换为整数,我们将打印出"无法将字符串转换为整数!"的错误信息;如果出现其他类型的错误,我们将打印出"未知错误!"的错误信息。在任何情况下,最后都会执行finally子句中的代码,确保文件被关闭。
阅读全文
相关推荐

















