You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中成功返回True、失败抛异常是否为良好编程实践?含代码示例

Hey there! Let's tackle your two Python questions clearly and practically:

1. Is it good practice for Python functions to return True on success and raise exceptions on failure?

Short answer: It depends on the context, but this pattern is absolutely acceptable and aligns well with Python's core philosophy of EAFP (Easier to Ask for Forgiveness than Permission). Here's a deeper breakdown:

  • When failures are unexpected, rare, or represent a genuine error state (not a normal part of your workflow), raising exceptions is a great choice. It forces callers to acknowledge and handle error scenarios (unless they explicitly choose to ignore them, which is their call).
  • That said, if a "failure" is an expected, frequent outcome (like checking if a user exists in a database), returning a boolean or an Optional value might be more intuitive—using exceptions for routine control flow can make code harder to read and less efficient.
  • Always use specific exception types instead of generic ones. For example, raise ValueError for invalid inputs or a custom FileProcessingError for file-related issues, rather than a vague Error. This lets callers catch exactly the errors they care about.
2. Is the provided function compliant for returning True only on success and raising an exception on failure?

First, let's look at your code again:

def a():
    try:
        b
    except Error:
        raise Error
    return True

This code has a few issues that make it non-compliant and functionally broken right now:

  • b is just a variable reference here, not a function call—if b isn't defined, it'll throw a NameError that won't be caught by except Error (since NameError doesn't inherit from Error in Python's standard hierarchy). If b is supposed to be a function, you need to write b().
  • Catching Error and immediately re-raising it is redundant—this does nothing except add unnecessary overhead. You could remove the entire try-except block and let the exception propagate naturally.
  • Error is not a standard exception type you should be catching. Most common exceptions inherit from Exception, not Error (which is a subclass of BaseException and includes things like SyntaxError that you usually don't want to catch).

That said, if you fix these issues, the intent is compliant. Here's a corrected version that does what you want:

def a():
    try:
        b()  # Execute the function b
    except SpecificError as e:
        # Optional: Add logging or cleanup here
        # print(f"Failed to run b: {str(e)}")
        raise  # Re-raise the original exception (preserves stack trace)
    return True

This revised version will return True only if b() executes without errors, and will propagate the exception if something goes wrong. Just remember to:

  • Catch specific exceptions instead of broad ones to avoid masking unexpected errors (like KeyboardInterrupt).
  • Include meaningful error messages in your exceptions to help debug issues later.

内容的提问来源于stack exchange,提问作者citruscake

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 11:12:57