Skip to content

异常

一句话解释

异常 是 错误 那个 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.

示例

python
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.

工作原理

  1. Code in try block runs normally.
  2. If an exception is raised, Python stops the try block.
  3. Python checks each except clause for a matching exception type.
  4. The first matching except block runs — this is your recovery code.
  5. If no except matches, the exception propagates up the call stack.

相关术语

相关资源

相关课程

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表