If you’re new to Python, do you often panic when your code throws an error? In fact, those red error messages are not to be feared; they are Python’s friendly way of telling you, “There’s a problem here.” Today, let’s talk about Python’s specialized “exception handling mechanism” that will help you not fear errors and easily manage your code!
⚠️ 1. Exception: A “Little Accident” in the Code World
First, you need to understand that an exception is an error that occurs during the execution of a program. For example, if you try to add a string and a number, Python will angrily throw a “TypeError”; if you attempt to open a non-existent file, you’ll encounter a “FileNotFoundError”.
These exceptions do not appear out of nowhere; they have a clear “lineage” like a family: the ancestor of all exceptions is “BaseException”, and it has an important branch called “Exception”, under which most of the errors we encounter (like the aforementioned TypeError) belong.
🛡️ 2. try-except: The “Shield” Against Exceptions
Since exceptions exist, there must be ways to deal with them, and “try-except” is the most commonly used “shield”. Its usage is simple: place the code that might cause a problem in the “try” block, and then specify what to do in the “except” block if a specific problem occurs.
try: num = int(input("Please enter a number: ")) print(10 / num)except ZeroDivisionError: print("The divisor cannot be 0!")except ValueError: print("Please enter a valid number!")
In the code above, if the input is not a number, it will trigger a “ValueError” and execute the corresponding message; if the input is 0, it will trigger a “ZeroDivisionError” and provide the appropriate reminder. This is multi-exception handling, which can accurately respond to different situations.
✅ 3. try-except-else: Execute Only When Everything Goes Smoothly
Sometimes, we want to execute some operations only when the code does not throw an exception, and this is where “else” comes into play.
try: num = int(input("Please enter a number: ")) result = 10 / numexcept (ZeroDivisionError, ValueError) as e: print("An error occurred: ", e)else: print("The result is: ", result)
When a valid number is entered and it is not 0, the code in the “else” block will execute, printing the calculation result.
🔒 4. try-except-finally: The “Cleanup Work” That Must Be Done
No matter whether an exception occurs or not, some operations must be performed, such as closing files or releasing resources; this is where “finally” is needed.
file = Nonetry: file = open("test.txt", "r") content = file.read() print(content)except FileNotFoundError: print("The file does not exist!")finally: if file: file.close() print("The file has been closed")
Regardless of whether the file was found or whether the content was successfully read, the code in the “finally” block will execute, ensuring that the file is closed.
🚨 5. Actively “Stir Trouble”: The raise Statement and Custom Exceptions
Sometimes, we need to actively throw exceptions to remind ourselves or others that there are issues in the code; this is where the “raise” statement comes in. Moreover, we can define exceptions based on our needs.
# Custom Exceptionclass AgeError(Exception): def __init__(self, message): self.message = messagetry: age = int(input("Please enter your age: ")) if age < 0 or age > 120: raise AgeError("Age must be between 0 and 120!")except AgeError as e: print("Invalid age input: ", e.message)except ValueError: print("Please enter a number!")
In this example, when the entered age is not within a reasonable range, we actively throw our defined “AgeError” exception.
🔗 6. Exception Chaining: The “Chain Reaction” of Errors
Sometimes, the occurrence of one exception may trigger another, like a domino effect; this is called exception chaining. We can clarify the causal relationship between exceptions using “raise…from”.
try: num = int(input("Please enter a number: ")) result = 10 / numexcept ValueError as e: raise RuntimeError("An error occurred while processing the input") from e
If the input is not a number, a “ValueError” will first occur, and then this exception will trigger a “RuntimeError”; by using “from e”, we associate these two exceptions, making it easier to trace the root of the error.
🎯 Summary: Exception Handling Makes Code More Robust
Mastering these syntax features of exception handling is like putting a “bulletproof vest” on your code, allowing you to walk more steadily and confidently on the path of programming. Remember the six core points discussed today:
- Exceptions are errors that occur during program execution and have a clear inheritance relationship.
- try-except is the basic structure for catching exceptions.
- The else block executes when there are no exceptions.
- The finally block ensures resource release and other cleanup work.
- The raise statement can actively throw exceptions.
- Custom exceptions and exception chaining can better handle complex errors.
🚀 Hands-on Practice
Now try using exception handling to solve these problems:
- Write a safe division calculator that handles division by zero and input errors.
- Create a file reading program that handles file not found and permission issues.
- Define a custom exception to validate the format of user input email addresses.
- Use finally to ensure file resources are correctly released.
