Python中成功返回True、失败抛异常是否为良好编程实践?含代码示例
Hey there! Let's tackle your two Python questions clearly and practically:
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
Optionalvalue 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
ValueErrorfor invalid inputs or a customFileProcessingErrorfor file-related issues, rather than a vagueError. This lets callers catch exactly the errors they care about.
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:
bis just a variable reference here, not a function call—ifbisn't defined, it'll throw aNameErrorthat won't be caught byexcept Error(sinceNameErrordoesn't inherit fromErrorin Python's standard hierarchy). Ifbis supposed to be a function, you need to writeb().- Catching
Errorand immediately re-raising it is redundant—this does nothing except add unnecessary overhead. You could remove the entiretry-exceptblock and let the exception propagate naturally. Erroris not a standard exception type you should be catching. Most common exceptions inherit fromException, notError(which is a subclass ofBaseExceptionand includes things likeSyntaxErrorthat 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

