Python standard exception and exception handling details
- 2020-04-02 14:34:25
- OfStack
Python provides two very important functions for handling exceptions and errors that occur when python programs are running. You can use this feature to debug python programs.
1. Exception handling: this is covered in the Python tutorial on this site.
Assertions: this is described in the Python tutorial.
Python standard exception
Unusual name | describe |
---|---|
BaseException | The base class for all exceptions |
SystemExit | The interpreter requests exit |
KeyboardInterrupt | User interrupt execution ( Usually the input ^C) |
Exception | Base class for general errors |
StopIteration | Iterators have no more values |
GeneratorExit | The generator (generator) An exception occurs to notify the exit |
SystemExit | Python The interpreter requests exit |
StandardError | Base class for all built-in standard exceptions |
ArithmeticError | Base class for all numeric errors |
FloatingPointError | Floating point error |
OverflowError | Numerical operation exceeded the maximum limit |
ZeroDivisionError | In addition to ( Or modulus ) zero ( All data types ) |
AssertionError | Assertion statement failed |
AttributeError | The object does not have this property |
EOFError | No built-in input , arrive EOF tag |
EnvironmentError | Base class for operating system errors |
IOError | The input / Output operation failed |
OSError | Operating system error |
WindowsError | System call failed |
ImportError | The import module / Object failed |
KeyboardInterrupt | User interrupt execution ( Usually the input ^C) |
LookupError | The base class for the invalid data query |
IndexError | There is no such index in the sequence (index) |
KeyError | There is no key in the map |
MemoryError | Memory overflow error ( for Python The interpreter is not fatal ) |
NameError | Not a statement / Initialize object ( There is no attribute ) |
UnboundLocalError | Accessing an uninitialized local variable |
ReferenceError | A weak reference (Weak reference) An attempt is made to access an object that has been garbage collected |
RuntimeError | Common runtime errors |
NotImplementedError | Methods that have not been implemented |
SyntaxError | Python Grammar mistakes |
IndentationError | The indentation error |
TabError | Tab Mixed with Spaces |
SystemError | General interpreter system error |
TypeError | An operation with an invalid type |
ValueError | An invalid parameter is passed in |
UnicodeError | Unicode Related error |
UnicodeDecodeError | Unicode Error in decoding |
UnicodeEncodeError | Unicode Coding error |
UnicodeTranslateError | Unicode Conversion error |
Warning | The base class for warnings |
DeprecationWarning | Warnings about deprecated features |
FutureWarning | There are warnings that the semantics of constructs will change in the future |
OverflowWarning | The old about auto promotion to long integer (long) The warning |
PendingDeprecationWarning | Warnings that features will be discarded |
RuntimeWarning | Suspicious runtime behavior (runtime behavior) The warning |
SyntaxWarning | Warning of questionable syntax |
UserWarning | User code generated warnings |
What is an exception?
An exception is an event that occurs during the execution of a program and affects the normal execution of the program.
Normally, an exception occurs when Python fails to handle the program properly.
An exception is a Python object that represents an error.
When an exception occurs in a Python script, we need to catch and handle it, or the program will terminate execution.
Exception handling
Exceptions can be caught using the try/except statement.
The try/except statement detects errors in the try statement block, allowing the except statement to capture exception information and handle it.
If you don't want to end your program when an exception occurs, just catch it in try.
Grammar:
Here is a simple try... . Except... Else syntax:
try:
< statements > # Run something else
except < The name > :
< statements > # If the try Part of it 'name' abnormal
except < The name > . < data >:
< statements > # If it triggers 'name' Exception to get additional data
else:
< statements > # If no exceptions occur
The way try works is that when a try statement is started, python marks it in the context of the current program so that it can come back here when an exception occurs, the try clause executes first, and what happens next depends on whether an exception occurs during execution.
1. If an exception occurs when a statement following the try executes, python jumps back to the try and executes the first except clause that matches the exception, the exception is handled, and the control flow goes through the entire try statement (unless a new exception is thrown when the exception is handled).
2. If an exception occurs in a statement after the try and there is no matching except clause, the exception is passed to the upper try or to the top of the program (this will end the program and print the default error message).
3. If no exception occurs during the execution of the try clause, python executes the statement after the else statement (if there is an else) and then controls the flow through the entire try statement.
The instance
Here is a simple example that opens a file and writes to the contents of the file without an exception:
#!/usr/bin/python
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print "Error: can't find file or read data"
else:
print "Written content in the file successfully"
fh.close()
Output results of the above program:
Written content in the file successfully
The instance
Here is a simple example, which opens a file, writes to the contents of the file, but the file has no write permission, and an exception occurs:
#!/usr/bin/python
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print "Error: can't find file or read data"
else:
print "Written content in the file successfully"
Output results of the above program:
Error: can't find file or read data
Use except without any exception type
You can use except without any exception type, as shown in the following example:
try:
You do your operations here;
......................
except:
If there is any exception, then execute this block.
......................
else:
If there is no exception then execute this block.
The above try-except statement captures all exceptions that occur. But this is not a good way, we can not identify the specific exception information through the program. Because it catches all exceptions.
Use except with multiple exception types
You can also use the same except statement to handle multiple exceptions, as shown below:
try:
You do your operations here;
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception list,
then execute this block.
......................
else:
If there is no exception then execute this block.
The try - finally statement
The try-finally statement executes the final code regardless of whether an exception occurs.
try:
< statements >
finally:
< statements > # exit try Time will always execute
raise
Note: you can use either the except or finally statements, but not both. The else statement also cannot be used with the finally statement
The instance
#!/usr/bin/python
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
finally:
print "Error: can't find file or read data"
If the open file does not have writable permissions, the output is as follows:
The same code at the page code block index 4
The same example can be written as follows:
#!/usr/bin/python
try:
fh = open("testfile", "w")
try:
fh.write("This is my test file for exception handling!!")
finally:
print "Going to close the file"
fh.close()
except IOError:
print "Error: can't find file or read data"
When an exception is thrown in the try block, the finally block code is executed immediately.
After all the statements in the finally block are executed, the exception is raised again and the except block code is executed.
The content of the parameter is different from that of the exception.
Abnormal parameters
An exception can take a parameter, which can be used as the output exception information parameter.
You can catch exception parameters with the except statement, as shown below:
try:
You do your operations here;
......................
except ExceptionType, Argument:
You can print value of Argument here...
The outliers received by a variable are usually contained in the statement of the exception. Variables can receive one or more values in the form of a tuple.
Tuples usually contain error strings, error Numbers, and error locations.
The instance
The following is an instance of a single exception:
#!/usr/bin/python
# Define a function here.
def temp_convert(var):
try:
return int(var)
except ValueError, Argument:
print "The argument does not contain numbersn", Argument
# Call above function here.
temp_convert("xyz");
The execution results of the above procedures are as follows:
The argument does not contain numbers
invalid literal for int() with base 10: 'xyz'
An exception
We can use the raise statement to raise the exception ourselves
The syntax of raise is as follows:
raise [Exception [, args [, traceback]]]
The Exception in the statement is the type of the Exception (for example, NameError) and the argument is an Exception parameter value. This parameter is optional; if not provided, the exception parameter is "None".
The last parameter is optional (rarely used in practice) and, if present, is to trace the exception object.
The instance
An exception can be a string, class, or object. Most of the exceptions provided by the Python kernel are instantiated classes, which are arguments to an instance of a class.
Defining an exception is as simple as this:
def functionName( level ):
if level < 1:
raise "Invalid level!", level
# The code below to this would not be executed
# if we raise the exception
Note: in order to catch exceptions, the except statement must have the same exception to throw a class object or string.
For example, if we catch the above exception, the "except" statement looks like this:
try:
Business Logic here...
except "Invalid level!":
Exception handling here...
else:
Rest of the code here...
User-defined exceptions
By creating a new exception class, programs can name their own exceptions. Exceptions should typically inherit from the Exception class, either directly or indirectly.
The following example is related to RuntimeError, where a class is created with the base class RuntimeError to output more information when an exception is triggered.
In the try block, the except block statement is executed after the user-defined exception, and the variable e is used to create an instance of the Networkerror class.
class Networkerror(RuntimeError):
def __init__(self, arg):
self.args = arg
After you define the above class, you can trigger the exception as follows:
try:
raise Networkerror("Bad hostname")
except Networkerror,e:
print e.args