异常
一句话解释
异常 是 错误 那个 occurs 虽然 你的 program 运行, 哪个 你 能 catch and handle 使用 try/except.
用大白话说
An exception is a runtime error — something that goes wrong while the program is executing. Dividing by zero, opening a missing file, or accessing a list index that does not exist all raise exceptions. If unhandled, the exception crashes the program with a traceback.
Python lets you catch exceptions with try/except blocks. Code that might fail goes in the try block, and the recovery code goes in except. This lets your program handle errors gracefully instead of crashing — show a friendly message, retry, or log the problem.
Every exception is an object with a type (like ZeroDivisionError or FileNotFoundError). You can catch specific types and let others propagate, or catch all exceptions with a bare except:. Good practice is to catch only the exceptions you expect and know how to handle.
示例
try:
number = int(input("Enter a number: "))
result = 10 / number
print(f"Result: {result}")
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("That was not a valid number.")try/except catches 特定 异常 类型. program handles 错误 相反 的 crashing.
工作原理
- Code in
tryblock runs normally. - If an exception is raised, Python stops the
tryblock. - Python checks each
exceptclause for a matching exception type. - The first matching
exceptblock runs — this is your recovery code. - If no
exceptmatches, the exception propagates up the call stack.
相关术语
相关资源
相关课程
- 条件 and 循环
异常 handling 构建 on control flow
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。