This article provides a detailed summary of Python standard exception development experience, which has some reference value, interested friends can refer to the many exceptions and errors we encounter when writing scripts or developing software. python has two very important functions, these two functions are exception handling and assertion.
Exception handling: mainly includes syntax errors and other standard exceptions. The following table describes standard exceptions.
Assertions: assertion is a rational check. when the program test is completed, you can open or close it. The simplest method of assertion is to compare it to the raise-if statement (or more accurately, add the raise-if-not statement ). if the result is false, an exception is thrown. Assert statements are used to introduce the new keywords in Python and the keywords used in Python1.5.
Programmers often place assertions to check the input validity, or check the output validity after a function call.
I. standard exception table
Exception example:
1. FileNotFoundError tries to open the file d: \ openstack.txt and reports FIleNotFoundError: f = open ("d: \ openstack.txt") Traceback (most recent call last) because the file does not exist ): file"
", Line 1, in
F = open ("d: \ openstack.txt") FileNotFoundError: [Errno 2] No such file or directory: 'd: \ openstack.txt '2. in ZeroDivisionError division or modulo operation, where the divisor is zero> 5/0 Traceback (most recent call last): File"
", Line 1, in
5/0 ZeroDivisionError: pision by zero3 and ImportError errors are generally reported when the module is imported because the module does not exist. >>> import wwtraceback (most recent call last): File"
", Line 1, in
Import wwwwImportError: No module named 'wwww '4. ValueError is generally caused by an error in the data type of the input parameter. >>> A = "sterc" >>> int (a) Traceback (most recent call last): File"
", Line 1, in
Int (a) ValueError: invalid literal for int () with base 10: 'sterc' >>>
II. Exception handling
Python contains two exception handling statements. you can use try... else t... finally or try... else t .. the following describes the syntax of the two statements and their differences:
Try statement principle:
First, execute the try clause (the statement between the keyword try and the keyword try t)
If no exception occurs, ignore the limit T clause. the try clause ends after execution.
If an exception occurs during the execution of the try clause, the remaining part of the try clause is ignored. If the type of the exception matches the name after the occurrence T, the corresponding occurrence T clause will be executed. The code after the try statement is executed.
If an exception does not match any except T, the exception will be passed to the upper-layer try.
A try statement may contain multiple distinct T clauses to handle different exceptions. At most one branch is executed.
The handler only processes exceptions in the corresponding try clause, rather than exceptions in other try programs.
A distinct T clause can handle multiple exceptions at the same time. these exceptions are placed in a bracket to become a tuples.
Try... syntax T... else syntax:
Try: You do your operations here ...................... except t ExceptionI: If there is ExceptionI, then execute this block. failed T ExceptionII: If there is ExceptionII, then execute this block ....................... else: If there is no exception then execute this block. A single try statement can have multiple limit T statements. When a try block contains a declaration that may throw different types of exceptions, this is useful. you can also provide a general rule T clause to handle exceptions (not recommended). then, you can include the else clause. If the code does not cause an exception in the try: Block, the code executes the else code in the else block and there is an exception in the normal operation department. This does not require the try: block protection try: fh = open ("testfile", "w +") fh. write ("This is my test file for exception handling !! ") Handle t IOError: print (" Error: can \'t find file or read data ") else: print (" Written content in the file successfully ") fh. after close () is executed normally, the content in the testfile file is generated as follows: This is my test file for exception handling! The console outputs the following results: Written content in the file successfully
Use the distinct T clause to handle multiple exceptions
In the preceding example, an exception of the type is handled, and the handle T can handle multiple types of exceptions, for example
Struct T (ValueError, ImportError, RuntimeError) this can be used to write multiple types of standard errors into a single tuple, but it is difficult to analyze the errors of our team type.
Try: fh = open ("testfile", "r") fh. write ("This is my test file for exception handling !! ") Failed t (ValueError, ImportError, RuntimeError): print (" Error: can \'t find file or read data ") else: print (" Written content in the file successfully ") fh. close () result: Error: can't find file or read data # no standard Error of that type is returned.
Try-finally clause:
Use try: the block. finally block must be executed, regardless of whether the try block causes exceptions or does not exist. The try-finally statement syntax is as follows.
try: You do your operations here; ...................... Due to any exception, this may be skipped.
except ExceptionI: If there is ExceptionI, then execute this block.except ExceptionII: If there is ExceptionII, then execute this block.
Finally:
This would always be executed.
Try... try t... finally no matter whether the try block can be executed normally, finally is the module that will be executed.
Try: fh = open ("testfile", "r") fh. write ("This is my test file for exception handling !! ") Failed t (ValueError, ImportError, RuntimeError): print (" Error: can \'t find file or read data ") finally: print (" Written content in the file successfully ") fh. close () # close file result: the file is not written, and the console outputs the following content: Error: can't find file or read dataWritten content in the file successfully
Exception
You can use the raise statement to trigger several exceptions. The syntax for raise statements is as follows.
Syntax
Raise [Exception [, args [, traceback]
Here, Exception is an Exception type (for example, NameError). argument is the parameter value of the Exception. This parameter is optional. if it is not provided, the exception parameter is None.
The last traceback parameter is also optional (rarely used in practice). if it exists, it is a backtracing object for exceptions.
Example
An exception can be a string, a class, or an object. The core of most Python exceptions is to trigger class exceptions and use an instance parameter exception of the class. It is easy to define new exceptions. you can do the following-
def functionName( level ): if level <1: raise Exception(level) # The code below to this would not be executed # if we raise the exception return level
Note: To catch exceptions, a "failed t" statement must indicate that a class object exception or a simple string exception is thrown. For example, to catch exceptions, we must write the limit T clause as follows-
try: Business Logic here...except Exception as e: Exception handling here using e.args...else: Rest of the code here...
The following example shows how to trigger an exception:
#!/usr/bin/python3def functionName( level ): if level <1: raise Exception(level) # The code below to this would not be executed # if we raise the exception return level try: l=functionName(-10) print ("level=",l)except Exception as e: print ("error in level argument",e.args[0])
This will produce the following results
Error in level argument-10
User-defined exceptions
In Python, you can also create your own exceptions through the built-in exception standard derived class.
Here is an example of RuntimeError. Here, a class is created, which is a subclass of RuntimeError. When necessary, an exception can be captured to display more specific information, which is very useful.
In the try block, user-defined exceptions will be thrown and caught in the limit T block. Variable e is used to create an instance with a network error Networkerror class.
class Networkerror(RuntimeError): def __init__(self, arg): self.args = arg
Therefore, after the above class definition, an exception can be thrown as follows-
try: raise Networkerror("Bad hostname")except Networkerror,e: print e.args
The above is a summary of Python standard exception development experience. For more information, see other related articles in the first PHP community!