When writing Python code, errors (or exceptions) are inevitable. How to gracefully handle errors, ensuring stable program operation while facilitating debugging, is a skill that every Python developer needs to master.
1. Exception Handling in Python
Exception handling is one of the important programming concepts in Python. If an exception error occurs in the code, it can cause the program to crash or fail to run properly. To avoid this situation, developers can use the try-except statement to catch and handle potential exceptions.
The basic syntax of the try-except statement block is as follows:

2. Example of Exception Handling (1)
In the following example, the program reads a user input value -> converts it to an integer -> outputs the result of 100 divided by that integer. The potential exceptions in the program are:
The input value is not an integer -> the program will throw an error when executing the int() function:
请输入一个整数:abcTraceback(most recent call last): File "G:\My Drivel100dayslexceptions.py", line 2,in <module> num = int(input("请输入一个整数:"))ValueError: invalid literal for int() with base 10: 'abc'
The input value is 0 or converts to 0 -> the program will throw an error when executing 100/num:
请输入一个整数:0Traceback(most recent call last): File "G:\My Drive\100days\exceptions.py", line 3, in <module> result = 100/numZeroDivisionError: division by zero
3. Example of Exception Handling (2)
For the previous program, the following modifications can be made:
-
Wrap the entire program content in a try statement for monitoring
-
If the program throws a ValueError, prompt the user to re-enter an integer
-
If the program throws a ZeroDivisionError, remind the user that it cannot be zero
-
If other unforeseen exceptions occur, use the except Exception as e statement to alias the exception and print it [this usage is typically chosen when the types of exceptions that may occur in the program cannot be predicted]
5. Print “Program Ended”
try: num = int(input("请输入一个整数:")) result = 100 / num print("结果为:", result)except ValueError: print("输入的不是整数,请重新输入")except ZeroDivisionError: print("除数不能为零,请重新输入")except Exception as e: print("未知错误:", e)finally: print("程序结束")
4. Ignoring Exceptions
Ignoring exceptions means not handling them when they occur, but rather skipping the exception and continuing program execution. This is often because certain exceptions do not affect the correct execution of the program under specific circumstances.
For example, when performing an operation to print the square of numbers in a list, the pass statement can be used in the except statement to skip non-numeric elements, thus avoiding program errors and termination.

5. Common Exception Types


Properly handling exceptions can improve the stability and reliability of the program, avoiding unpredictable erroneous behavior.
For more Python learning materials, those in need can leave a comment with 999. I will share all my valuable resources with you!