error-handling

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Error Handling

错误处理

Use Specific Exceptions

使用特定异常

When using try-except blocks, limit the except to the smallest set of errors possible.
Don't:
python
try:
    open(path, "r").read()
except:
    print("Failed to open file")
Do:
python
try:
    open(path, "r").read()
except FileNotFoundError:
    print("Failed to open file")
在使用try-except代码块时,应将except捕获的错误范围限制在最小的可能集合内。
错误示例:
python
try:
    open(path, "r").read()
except:
    print("Failed to open file")
正确示例:
python
try:
    open(path, "r").read()
except FileNotFoundError:
    print("Failed to open file")