Python's strongest leader (10) -- exception, pythonexception
1. Python exception handling
Python provides two very important functions to handle exceptions and errors in the running of python programs. You can use this function to debug python programs.
- Exception Handling: the Python tutorial on this site will be detailed.
- Assertions.
2. What is an exception?
An exception is an event that occurs during program execution and affects normal execution of the program.
Generally, an exception occurs when Python cannot process the program normally.
An exception is a Python object, indicating an error.
When a Python script exception occurs, we need to capture and process it; otherwise, the program will terminate the execution.
3. Exception Handling
You can use the try/try t statement to catch exceptions.
The try/try t statement is used to detect errors in the try statement block, so that the try t statement can capture and handle exceptions.
If you don't want to end your program when an exception occurs, just capture it in try.
Syntax:
The following is a simple try... example t... else Syntax:
Try: <Statement> # Run another code except T <name>: <Statement> # If 'name' exception occurs in try <name>, <DATA>: <Statement> # If a 'name' exception is thrown, obtain the additional data else: <Statement> # If no exception occurs
The try clause works as follows: after a try statement is started, python marks it in the context of the current program. In this way, when an exception occurs, the try clause can be executed first, what will happen next depends on whether exceptions occur during execution.
If an exception occurs during statement execution after try, python will jump back to try and execute the First alias t clause that matches the exception. The Exception Processing is complete, the control flow uses the entire try Statement (unless a new exception is thrown when an exception is handled ).
If an exception occurs in the statement after try, but there is no matching limit t clause, the exception will be submitted to the try at the upper layer or to the upper layer of the Program (this will end the program, and print the default error information ).
If no exception occurs during the execution of the try clause, python will execute the statement after the else Statement (if else exists) and then control the flow through the entire try statement.
Example 1:
#! /Usr/bin/env python #-*-coding: UTF-8-*-# @ Time: 2016/9/29 # @ Author: wwyxtry: ft = open ("testFile.txt ", "w") ft. write ("test exception! @! ") Failed t IOError: print" An error occurred while writing the file! "Else: print" file written successfully! "Ft. close ()
Example 1 running result
File written successfully!
For the testFile.txt file in Example 1, we set its attribute to read-only, and then we run the program
Modified program running result:
An error occurred while writing the file!
4. try-finally statement
The try-finally statement executes the final code no matter whether an exception occurs.
Try: <Statement> finally: <Statement> # raise is always executed when you exit try.
5. Abnormal Parameters
An exception can contain parameters that can be used as output exception information parameters.
You can capture the exception parameters through the explain T statement, as shown below:
Try: normal operation ...................... failed t ExceptionType, Argument: You can output the Argument value here...
Abnormal Values received by variables are usually included in abnormal statements. In the form of tuples, a variable can receive one or more values.
Tuples usually contain error strings, error numbers, and error locations.
Instance 2
#! /Usr/bin/env python #-*-coding: UTF-8-*-# @ Time: 2016/9/29 # @ Author: wwyxdef convert (var): try: I = int (var) failed t ValueError, Argument: print "Value Type Error:", Argument else: print "execution successful !! "# Call the function convert (" sdsf ")
Example 2 running result
Value Type Error: invalid literal for int () with base 10: 'sdsf'
6. Trigger an exception
We can use the raise statement to trigger exceptions ourselves.
The raise syntax format is as follows:
raise [Exception [, args [, traceback]]]
In a statement, the Exception type (for example, NameError) parameter is an Exception parameter value. This parameter is optional. If this parameter is not provided, the exception parameter is "None ".
The last parameter is optional (rarely used in practice). If so, it is a trace exception object.
An exception can be a string, class, or object. The exception provided by the Python kernel is mostly instantiated classes, which are the parameters of a class instance.
Defining an exception is very simple.
Example 3:
#! /Usr/bin/env python #-*-coding: UTF-8-*-# @ Time: 2016/9/29 # @ Author: wwyxdef convert (var): if (var> 2 ): raise Exception ("Invalid value:", var) # Call the function try: convert (3) failed t "Invalid value:": print 1 else: print 2
Example 3 running result
Traceback (most recent call last): File "E:/python/hello/untitled3/exception.py", line 12, in <module> convert(3) File "E:/python/hello/untitled3/exception.py", line 7, in convert raise Exception("Invalid value:", var)Exception: ('Invalid value:', 3)
7. User-defined exceptions
By creating a new exception class, programs can name their own exceptions. Exceptions are typically inherited from the Exception class, either directly or indirectly.
The following is an instance related to RuntimeError. A class is created in the instance. The base class is RuntimeError, which is used to output more information when an exception is triggered.
In the try statement block, execute the limit t BLOCK statement after a custom exception. The variable e is used to create an instance of the Networkerror class.
Example 3:
#!/usr/bin/env python# -*- coding: utf-8 -*-# @Time : 2016/9/29 21:28# @Author : wwyxclass Networkerror(RuntimeError): def __init__(self, arg): self.args = argtry: raise Networkerror("Bad hostname")except Networkerror,e: print e.args
Example 3 running result:
('B', 'a', 'd', ' ', 'h', 'o', 's', 't', 'n', 'a', 'm', 'e')