Python-exception Basics
Exception Basics
In Python, exceptions are automatically triggered Based on errors, and can also be triggered and intercepted by code. Exceptions are handled by five statements:
1. [try/try t]: capture and recover exceptions caused by Python or you.
2. [try/finally]: Clean up whether or not an exception occurs.
3. [raise]: manually trigger an exception in the code.
4. [assert]: triggers an exception in the program code conditionally.
5. [with/as]: implement the Environment Manager in Python2.6 and later versions
Exceptions can be used for various purposes. The following are the most common roles:
1. Error Handling: every time a program error is detected at runtime, Python will cause an exception. You can capture the error in the code or ignore the exception that has occurred.
2. Event Notification: An exception can also be used to send a valid state signal, without passing a result flag between programs or deliberately testing it.
3. special case handling: Sometimes, it is rare to adjust the code to handle such rare cases. Usually, the exception processor processes these rare cases, thus eliminating the need for special cases of code.
4. Termination: The try/finally statement ensures that the end operation is required, regardless of whether an exception exists in the program.
5. unconventional Control Process
Certificate -----------------------------------------------------------------------------------------------------------------------------------
Default exception Processor
Let's write the following functions:
>>> def fetcher(obj,index):return obj[index]
In normal operations, it returns the results of valid index values:
>>> x = 'spam'>>> fetcher(x,3)'m'
However, if the index points to the position after the end of the string, an exception is thrown. Python detects the index operation that exceeds the boundary for the sequence, and reports the built-in IndexError through [throw.
>>> fetcher(x,4)Traceback (most recent call last): File "
", line 1, in
fetcher(x,4) File "
", line 2, in fetcher return obj[index]IndexError: string index out of range
Because our code does not capture this exception, it will always return to the top layer of the program and enable the [Default exception processor]: print the standard error message.
Certificate -----------------------------------------------------------------------------------------------------------------------------------
Capture exceptions
However, in some cases, this is not what we want. For example, a server program usually needs to keep working when an internal error occurs. If you do not want the default abnormal behavior, you need to wrap the call in the try statement to capture exceptions on your own.
>>> try:fetcher(x,4)except IndexError:print('got exception')got exceptionNow, if an exception is triggered when the try code block is executed, Python will automatically jump to the processor (the code block under the commit t clause that points to the Exception name ). In the actual program, the try statement not only captures exceptions, but also resumes execution:
>>> def catcher():try:fetcher(x,4)except IndexError:print('got exception')print('continuing')>>> catcher()got exceptioncontinuingThis time, after exception capturing and processing, the program continues to execute after capturing the entire try statement: this is why the message "continuing" is obtained. We didn't see the standard error message, and the program will run normally.
========================================================== ==========================================
User-defined exceptions
A user-defined Exception can be written through a class. It inherits from a built-in Exception class. Generally, the class name is Exception.
>>> class Bad(Exception):pass>>> def doomed():raise Bad()>>> try:doomed()except Bad:print('Got Bad')Got Bad
========================================================== ==========================================
Termination
Finally, the try statement can contain the finally code block, which defines the final behavior during the final execution, regardless of whether an exception occurs in the try code block.
>>> try:fetcher(x,3)finally:print('after fetch')'m'after fetchHere, if there is no exception after the try code block is completed, the finally code block will be executed, and the program will continue after the try.
Later, we will see that Python2.6 and Python3 provide a try/finally alternative when using some types of objects. With/as runs the environment management logic of an object to ensure termination:
>>> with open('test.txt','w') as file:file.write('The night!')