Detailed explanation of Python error handling mechanism
In program development, no matter how careful you are in writing code, runtime errors are inevitable - such as zero encountered during division, failure to convert a string to a number, or opening a non-existent file.
In the early days, many languages relied on the "return error code" method to handle exceptions. However, the shortcomings of this solution are obvious: normal results and errors are mixed together and it is difficult to distinguish. Every time a function is called, a judgment must be made. When reporting with multiple layers of nesting, the code will become redundant and difficult to read.
Fortunately, Python provides a set oftry...except...else...finally...The structured exception-handling mechanism completely separates error handling logic and business logic, making the code elegant and robust.
1. Core usage of try-except
1.1 Basic process demonstration
Let’s look at the most classic example first:
The running process can be summarized in one sentence:
Rush first
tryblock, if an error occurs, the corresponding one will be jumped.except, leave no matter whatfinally, and finally the program ends normally.
2. Advanced: multiple exceptions and else clauses
2.1 Catching various exceptions
A piece of code may throw multiple errors, we can write multipleexceptProcessed separately:
2.2 else when there is no error
iftryThe block ** does not throw an exception at all ** and will be executed.elseClause - The advantage of this design is that it clearly separates "business logic" and "supplementary logic after error-free":
3. Inheritance relationship of Python exceptions
All exceptions in Python are objects and inherit from the top-level base classBaseException. In our usual development, 99% of the time we only need to capture its subclassesExceptionor more specific exception type.
Several common exception levels:
BaseException(Top level, generally not captured directly)Exception(General error base class, commonly used in development)ArithmeticError(arithmetic error base class)ZeroDivisionError(divide by zero/modulo zero)
LookupError(index/key error base class)IndexError(list out of bounds)KeyError(key that does not exist in dictionary)
TypeError(Type mismatch, such as givinglen()Passed an integer)ValueError(Invalid value, e.g.int('abc'))OSError(Base class for operating system errors, such as opening a file that does not exist)
The complete hierarchy can be found in Python 官方异常文档.
4. Debugging tool: call stack Traceback
When you do not catch an exception, Python will automatically print out a detailed call chain (Traceback) to help you quickly locate the error's "trigger point" and "propagation path."
4.1 Call stack example
Output after running:
4.2 How to quickly read the call stack
Remember to read from bottom to top:
- The last line is error type and core reason (this is the key to solving the problem)
- Going up are the calls at each layer of the propagation chain: the closest one is the trigger point, and the farthest one is the program entry.
5. Record errors without interrupting the program: logging module
If you don’t want the program to crash because of an error, and you need to completely record the error information (such as Traceback), you can use Python’s built-inloggingModule:
6. Custom exceptions and exception delivery
6.1 Custom exceptions
When the built-in exception types are not enough, you can inheritException(or its appropriate subclass) define your own exception:
Best Practices for custom exceptions:
- Prioritize the use of built-in exceptions (don’t reinvent the wheel)
- Only customize when "there is special processing logic" or "clearer semantics are needed"
- The inheritance relationship must be reasonable (such as "invalid age" inheritance
ValueErrorinstead ofOSError)
6.2 Exception delivery (rethrow)
Sometimes we catch an exception not to handle it, but to do some recording or conversion, and then throw it to the upper caller for processing:
Another scenario is to convert the exception type:
7. 5 best practices for error handling
-
Capture accurately, don’t grab randomly Only catch exceptions that you know how to handle, such as just catching
FileNotFoundErrorThat's enough. Don't grab them as soon as you come up.ExceptionevenBaseException。 -
Avoid empty except
except:All exceptions will be caught (including keyboard interruptsCtrl+C), it is very dangerous and should never be written. -
try block should be small Only put in "the line/lines that may throw an exception", don't wrap the entire function.
-
Throw exceptions with context For example, don’t just write
raise ValueError, to writeraise ValueError(f'无效参数:{s},应该是数字')。 -
Documentation of possible exceptions Write clearly in the docstring of the function what exceptions will be thrown and why.
8. Small exercise: Repair a summation code
Practice code
Repair ideas
Revisestr2numFunction, try to convert to integer first, then convert to floating point number after failure:
Summarize
Python’s structured exception-handling is a core tool for writing reliable software:
- It completely separates business logic and error handling
- Call stack Traceback helps you quickly locate problems
- Custom exceptions and delivery make error handling more flexible
Remember: Error handling is not to "cover errors", but to "handle errors gracefully, provide useful information, and ensure that the program runs within a controllable range".

