Skip to content

异常 and 错误 Handling

Handle 错误 gracefully 使用 try/except/else/最后, raise 异常, and 创建自定义 ones.

你将学到

  • Use try/except 到 catch and handle 错误
  • 理解 else and 最后 clauses
  • Raise 异常使用 raise and assert
  • 创建自定义异常类
  • Avoid catching 也 broad or 也 narrow 异常

概念讲解

try / except

Python uses try/except to handle errors (exceptions). Code that might fail goes in the try block; the handling code goes in except:

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot 划分通过零!")
    result = None

If no exception occurs, the except block is skipped. If an exception of the specified type occurs, the except block runs. If an unlisted exception occurs, it propagates up.

Catching Multiple Exceptions

try:
    value = int(input("输入数字: "))
    result = 100 / value
except ValueError:
    print("那个是 不有效数字")
except ZeroDivisionError:
    print("Cannot 划分通过零")
except (TypeError, OverflowError):
    print(" 不同错误 occurred")

You can catch multiple types in one except by passing a tuple. Always catch specific exceptions — never use a bare except: without a type, as it hides bugs.

else and finally

try:
    f = open("数据.txt")
except FileNotFoundError:
    print("File 不找到")
else:
    # Runs only if NO exception occurred
    print(f.read())
    f.close()
finally:
    # ALWAYS runs, exception or not
    print("Cleanup 完整")
  • else — runs only if the try block succeeded with no exception. It is cleaner than putting success logic inside try.
  • 最后 — always runs, whether an exception occurred or not. Use it for cleanup (closing files, releasing resources).

Raising Exceptions

Use raise to trigger an exception intentionally:

def set_age(age):
    if age < 0:
        raise ValueError("Age cannot 是负")
    return age

# Re-raise an exception after logging
try:
    risky_operation()
except Exception as e:
    log_error(e)
    raise  # re-raises the same exception

The raise statement without arguments re-raises the current exception — useful for logging and propagating.

The Exception Hierarchy

All exceptions derive from BaseException. The most common ones:

BaseException
├── SystemExit          # sys.exit()
├── KeyboardInterrupt   # Ctrl+C
└── Exception
    ├── StopIteration
    ├── ArithmeticError
    │   └── ZeroDivisionError
    ├── LookupError
    │   ├── IndexError
    │   └── KeyError
    ├── ValueError
    ├── TypeError
    ├── FileNotFoundError
    └── ...

Catch 异常 (not BaseException) if you want to catch all "normal" errors without intercepting SystemExit and KeyboardInterrupt.

Custom Exceptions

Create your own exception classes by inheriting from 异常:

class InvalidAgeError(ValueError):
    """Raised 当 age 值是 无效."""
    pass

def set_age(age):
    if age < 0:
        raise InvalidAgeError(f"Age cannot 是负: {age}")
    return age

Custom exceptions make your error handling more meaningful and let callers catch your specific errors separately from built-in ones.

Getting Exception Details

try:
    risky_code()
except Exception as e:
    print(f"错误类型: {类型(e).__name__}")
    print(f"错误消息: {e}")

The as e syntax binds the exception object to a variable so you can inspect it.

示例代码

              # Basic try/except
try:
    result = 10 / 0
except ZeroDivisionError as e:
    print(f"Caught: {e}")
    result = None
print(f"Result: {result}")

# Multiple exception types
try:
    value = int("not a number")
    result = 100 / value
except ValueError:
    print("That is not a valid number")
except ZeroDivisionError:
    print("Cannot divide by zero")

# else and finally
try:
    number = int("42")
except ValueError:
    print("Invalid input")
else:
    print(f"Success: got {number}")
finally:
    print("Cleanup runs always")

# Raising exceptions
def set_age(age):
    if age < 0:
        raise ValueError(f"Age cannot be negative: {age}")
    return age

try:
    set_age(-5)
except ValueError as e:
    print(f"Validation error: {e}")

# Custom exception
class InvalidScoreError(ValueError):
    """Raised when a test score is out of range."""
    pass

def check_score(score):
    if not 0 <= score <= 100:
        raise InvalidScoreError(f"Score must be 0-100, got {score}")

try:
    check_score(150)
except InvalidScoreError as e:
    print(f"Score error: {e}")
            

Demonstrates 基础 try/except, catching 多个类型, else/最后 clauses, raising ValueError 使用消息, re-raising, and 自定义异常类 inheriting 从 ValueError.

动手试一试

  • JSON Formatter

    JSON parsing 错误是 常见 — 练习 handling malformed 输入.

  • Math Evaluator

    Math 错误如 division 通过零 是 classic 异常情况.

常见错误

错误写法

Using bare except: 那个 catches 所有异常包含 KeyboardInterrupt

正确做法

从不 use bare 'except:' — 它 catches SystemExit and KeyboardInterrupt 也, 制作 Ctrl+C 不工作. Use 'except 异常:' at 最小值, or better, catch 特定异常类型.

错误写法

Catching 异常也 broadly and silently ignoring 错误

正确做法

Avoid 'except 异常: 通过' — 它 hides bugs. 总是 at 最少 log 异常. Catch 仅特定异常你 expect and know 如何 handle. Let unexpected 错误 propagate.

相关速查表

练习 异常 and 错误 Handling

8 个练习

练习 异常 and 错误 Handling

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

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

查看错误