Exception (runtime error ):
When an unexpected event occurs in the Code logic, such as opening a file, the file does not exist. Does it add additional code processing logic or capture exceptions? The answer is: it is recommended that exceptions be caught in Python first and then restored.
Python exception Mechanism
Handle exceptions as normal. First, try the code that may cause exceptions during the test run. If any exceptions occur, capture them and restore them.
Additional code and logic, or exception handling?
1. Add additional code and logic. The more errors you consider, the more code and logic you want to add until the program's original logic may be concealed. The exception handling solution does not have this problem. You can clearly see the main logic of the program using exception handling.
2. It is hard for you to consider all possible errors. The exception handling mechanism can be used to easily handle all exceptions.
3. Adding additional code and logic leads to too much coupling with actual errors, and the code will change with the situation. Exception Handling only needs to focus on the exception.
4. Using the Exception Handling Mechanism of Python, you can focus on what the program really needs to do, instead of worrying about where the problem may occur, and write additional code to avoid running errors.
5. Simply put, using additional code and logic will increase complexity, which will cause trouble for debugging and code correction. The exception handling mechanism of Python allows you to focus on the main logic of the Code.
Therefore, the exception handling mechanism is recommended.
Python exception mechanism details:
General Processing
Try:
# Code with exceptions
Except t:
# Error recovery code
Handle specific exceptions
Try:
# Code with exceptions
Except t exception:
# Code for handling specific exceptions
Make sure that some code is executed no matter whether exceptions occur or not.
Ry:
# Code with exceptions
Except t exception:
# Code for handling specific exceptions
Finally:
# Code that will be executed
PS:
When handling exceptions, you can simply ignore exceptions using the pass statement in the exception handling code. The pass statement is an empty Python statement and does nothing.
In python, A valueerror exception occurs when the data does not conform to the expected format. Ioerror occurs when data cannot be accessed normally.