This article mainly introduces the exception handling tutorial in Python programming. It is the basic knowledge in getting started with Python. For more information, see
1. Exception Overview
In terms of software, errors are syntactically or logically. When python detects an error, the interpreter will point out that the current stream can no longer be executed, and an exception occurs. Exceptions are divided into two phases: first, errors that cause exceptions, and then possible measures. Common exceptions include:
NameError, ZeroDivisionError, SyntaxError, IndexError, KeyError, IOError, AttributeError, ValueError,
TypeError. All standard/built-in exceptions are derived from root exceptions. Currently, there are three Exception subclasses directly derived from BaseException: SystemExit, KeyboardInterrupt, and Exception. All other built-in exceptions are subclasses of Exception.
2. exception detection and handling
The try statement can be used to detect exceptions. There are two main forms: try-try t and try-finally. The former can add an optional else clause to handle situations where no exceptions are detected. A try statement can correspond to one or more distinct T statements, but can only correspond to one finally clause. Limit T is used to capture and handle exceptions and can handle multiple exceptions, you can also specify an optional exception parameter (it will be a class instance containing diagnostic information from the Exception Code, and the exception parameter itself will constitute a tuple, and stored as the attributes of the class instance), to avoid the bare volume T (will capture all exceptions, there is no chance to save the cause of exceptions, although you can use sys. obtained by exc_info (), but not recommended. If you want to catch all exceptions, you can use the BaseException class in counter t, and the Exception class does not include KeyboardInterrupt and SystemExit ), finally is executed no matter whether an error occurs or not. Try-try t-finally is a composite statement. When a try detects an exception, the remaining code in the try statement block will not be executed, and the exception will be extended to the stack and submitted up until a suitable exception processor is found, if the corresponding processor is still not found at the top layer, the python interpreter displays the trace return message and exits.
Try-try t Syntax:
try: try_suite except Exception1[, reason1]: suite_for_exception_ Exception1 except Exception2[, reason2]: suite_for_exception_ Exception2 except (Exception3, Exception4)[, reason3_4]: suite_for_exceptions_ Exception3_and_Exception4 except (Exc5[, Exc6[, ... ExcN]])[, reason]: suite_for_exceptions_ Exc5_to_ExcN else: suite_for_no_exception finally: suite_always_run
Multiple exceptions can be captured at the same time, exception objects can be captured, and exception types can be ignored to capture all exceptions
>>> Try: x = int (input ('input x: ') y = int (input ('input y:') print ('x/y = ', x/y) except t ZeroDivisionError: # Catch print ("ZeroDivision") except 0 exception T (TypeError, ValueError) as e: # Catch multiple exceptions, print (e) The exception object output T: # capture other types of exceptions print ("it's still wrong") input x: 12 input y: 0 ZeroDivision >>> try: x = int (input ('input x: ') y = int (input ('input y:') print ('x/y = ', x/y) except t ZeroDivisionError: # capture print ("ZeroDivision") except 0 exception T (TypeError, ValueError) as e: # capture multiple exceptions and output print (e) into T: # capture other types of exceptions print ("it's still wrong") input x: 12 input y: y invalid literal for int () with base 10: 'y'
Try/try t can be added with the else statement to implement what to execute when there is no exception
>>> Try: x = int (input ('input x: ') y = int (input ('input y:') print ('x/y = ', x/y) except t ZeroDivisionError: # capture print ("ZeroDivision") except 0 exception T (TypeError, ValueError) as e: # capture multiple exceptions print (e) failed t: # capture other types of exceptions print ("it's still wrong") else: # Run print ('It work well') input x: 12 input y: 3 x/y = 4.0 it work well
3. with statements in context management
As mentioned above, try-again t and try-finally, python has done a lot of work on hiding details, so you only need to worry about how to solve your problems. Another example of hiding low-level abstraction is the with statement, which is officially enabled in python2.6. Python2.5 tries to introduce with and sends such a warning to applications that use with as the identifier-In python2.6, with will become a keyword. If you want to use the wiht statement in python2.5, you must use from _ fututure _ import with_statement to import it.
Similar to try-ahead T-finally, the with statement is also used to simplify the Code. This should be the same as the thousands of calls that try-ahead T and try-finally want to achieve. A specific combination of try-finally t and try-finally is to ensure the unique allocation of shared resources and release it at the end of the task. For example, files (data, logs, databases, etc.), thread resources, simple synchronization, database connections, etc. The with statement is used in this scenario. However, the purpose of the with statement is to remove the "try", "try", and "finally" keywords and Code related to resource allocation and release from the flowchart, rather than simply simplifying the Code to make it easy to use, as the "try-release T-finally" statement does. The basic usage of the with syntax is as follows:
with context_expr [as var]: with_suite
It looks so simple, but with can only work on objects that support context management protocols. When the with statement is executed, context_expr is executed to obtain a context manager. Its responsibility is to provide a context object, which is implemented by calling the _ context _ () method. Once we obtain the context object, we will call its _ enter _ () method. When the with statement block is executed, the _ exit _ () method of the context object is called. There are three parameters. If the with statement block ends normally, all three parameters are None, if an exception occurs, the values of the three parameters are the same as those of sys. the exc_info () function returns three values: type (exception class), value (exception instance), and traceback. The contextlib module helps you compile the context manager of an object.
Common exceptions:
Exception: base classes of all exceptions
AttributeError is triggered when an application or value assignment fails.
When IOError attempts to open a nonexistent file
IndexError is triggered when an index does not exist in the sequence is used.
KeyError is triggered when a key that does not exist in the ing is used.
NameError is triggered when no name (variable) is found.
SyntaxError is triggered when the code is in the error format
If TypeError is applied to an object of the error type
The ValueError operation or function is applied to objects of the correct type.
ZeroDivisionError is triggered when the second parameter of the division or division operation is 0.
4. custom exception:
Class inherited from Exception
class myException(Exception):pass
5. Throw an exception:
Raise statement
>>> def pision(x,y): if y == 0 : raise ZeroDivisionError('The zero is not allow') return x/y >>> try: pision(1,0) except ZeroDivisionError as e: print(e) The zero is not allow
6. finally statement
Whether or not an exception occurs, finally statement block content will be executed at last for cleanup.
Therefore, you can close the file in the finally statement to ensure that the file can be closed normally.
>>> Try: x = int (input ('input x: ') y = int (input ('input y:') print ('x/y = ', x/y) except t ZeroDivisionError: # capture print ("ZeroDivision") except 0 exception T (TypeError, ValueError) as e: # capture multiple exceptions print (e) failed t: # capture other types of exceptions print ("it's still wrong") else: # Run print ('It work well') finally if no exception occurs: # print ("Cleaning up") input x: 12 input y: 3 x/y = 4.0 it work well Cleaning up
After an exception is thrown, if it is not received, the program will throw it to the previous layer. For example, if the function call is still not received, it will continue to throw, if the program does not handle this exception at the end, it will be thrown to the operating system-your program crashes, which is the same as C ++.