异常处理实践:Python中try/except语句的典型应用实例
在Python编程中,try/except
语句是处理可能发生的异常的一种方式。下面是一些典型的应用实例:
文件操作:
try:
with open('example.txt', 'r') as file:
content = file.read()
print(content)
except FileNotFoundError:
print("The file 'example.txt' does not exist.")
这里,如果文件不存在,会捕获
FileNotFoundError
异常并进行处理。数据库操作:
```python
import sqlite3
try:
conn = sqlite3.connect(‘my_database.db’)
cursor = conn.cursor()
cursor.execute(“SELECT * FROM my_table WHERE condition=true”)
results = cursor.fetchall()
print(results)
except sqlite3.Error as e:
print(f”SQLite error: {e}”)
finally:
if conn:
cursor.close()
conn.close()``
这里,如果数据库操作过程中出现错误,会捕获
sqlite3.Error`异常并进行处理。
以上就是使用Python的try/except语句处理常见异常的一些典型应用实例。
还没有评论,来说两句吧...