Python's exception concept introduction and handling

1. What is exception handling

Definition: Exception handling is the error message we often see when writing Python, such as; NameError, TypeError, ValueError, etc. These are all exceptions.

An exception is an event. The change event will occur during the execution of the program and affect the normal execution of the program. Under normal circumstances, an exception will occur when the program cannot be processed in python. An object in Python represents an error. When an exception occurs in the script, we need to catch and handle the exception, otherwise the program will terminate execution.

Two, exception handling

What do we do when there is an exception in the Python script?

Just as the tool we use has a little problem, we can find a way to fix it, and the program is the same. After continuous accumulation and thinking, the previous predecessors have created many good ways to deal with abnormalities in the program. In this chapter, we will Talk about using try statement to handle exceptions.

First, let's talk about the syntax of the try statement:

The try statement is used in combination with the except. This statement is used to detect errors in the try statement block, so that the except statement can capture the exception information and handle it. If you don’t want to end the program when an exception occurs, you only need to catch the exception in the try statement.

try:
< Code block
except <Exception name
print(&#39;Statement')
Examples are as follows:
def func():try:
a = x/y
print('a=',a)return a
eccept Exception:print('The program is abnormal, and the abnormal information: the dividend is 0')

Three, throw an exception

Use the raise statement to throw a specified exception in Python. We can call the raise statement with class or instance parameters to raise an exception.
Examples are as follows:

classEvaException(BaseException):
def __init__(self,msg):
self.msg=msg
def __str__(self):return self.msg

try:
raise EvaException('Type error')
except EvaException as e:print(e)

Four, catch multiple exceptions

We talked about how to deal with an abnormal situation, if there are more than one, how should we deal with it?

In Python, a try/except statement is supported to handle multiple exceptions. The syntax is as follows:

try:<Statement
except <Exception name:
print(&#39;Exception description')
except <Exception name:
print(&#39;Exception description')
The try statement works as follows:
The statement block in the try is executed for the first time. If no exception occurs, the words in except are ignored, and the code block in the try statement ends after execution. If the code block in the try statement is abnormal, the remaining statements in the try will be ignored.
If the exception and the exception name in eccept are the same, the corresponding except statement will be executed. If an exception does not match, the exception will be passed to the upper try statement, a statement may contain the first except statement,
Handle different exceptions separately, but at most only one branch will be executed.
try:
# a
#1 /0
dic ={1:2}
dic[3]
except NameError:print('The name is not defined, an error is reported')
except ZeroDivisionError:print('0 cannot be used as a divisor, an error is reported')
except KeyError:print('No this key')

Five, abnormal else

What if we want to do other things after the program is executed abnormally?

At this time, we can use the else in the exception. The specific syntax is as follows:

try:<Statement
except <Exception name:
< Statement
except <Exception name:
< Statement
else:
< Statement#(Execute this code after there is no exception in the try statement)
If no exception occurs in the try statement, the else statement will be executed. It is better to use the else statement than putting all the statements in the try clause. This can avoid some unexpected exceptions that are not caught by except:
def func(x,y):try:
a = x/y
except :print('Error,happened')else:print('It went as execpt')func(2,1)

Six, user-defined exceptions

You can have your own exceptions by creating a new exception class. Exceptions should inherit from the Exception class, either directly or indirectly, for example:

classMyError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):returnrepr(self.value)try:
raise MyError(2*2)
except MyError as e:print('My exception occurred, value:', e.value)

My exception occurred, value:4
raise MyError('oops!')Traceback(most recent call last):
File "<stdin ", line 1,in?
main__.MyError:'oops!'
In this example, the default class Exception__init__()Is covered.

When creating a module may throw a variety of different exceptions, a common practice is to create a basic exception class for the package, and then create different subclasses for different error conditions based on this basic class:classError(Exception):"""Base class for exceptions in this module."""
pass

classInputError(Error):"""Exception raised for errors in the input.

Attributes:
expression -- input expression in which the error occurred
message -- explanation of the error
"""

def __init__(self, expression, message):
self.expression = expression
self.message = message

classTransitionError(Error):"""Raised when an operation attempts a state transition that's not
allowed.

Attributes:
previous -- state at beginning of transition
next -- attempted newstate
message -- explanation of why the specific transition is not allowed
"""

def __init__(self, previous, next, message):
self.previous = previous
self.next = next
self.message = message
Most of the abnormal names start with"Error"At the end, just like the standard exception naming.

Seven, define cleanup behavior (finally statement)

The try statement has another optional clause, which defines the cleanup behavior that will be executed under any circumstances. E.g:

try:... raise KeyboardInterrupt
... finally:...print('Goodbye, world!')... 
Goodbye, world!Traceback(most recent call last):
File "<stdin ", line 2,in<module 
KeyboardInterrupt
The above example will execute the finally clause regardless of whether an exception occurs in the try clause.

If an exception is thrown in the try clause (or in the except and else clauses) and there is no except to intercept it, then the exception will be thrown again after the finally clause is executed.

The following is a more complex example (contains except and finally clauses in the same try statement):

 def divide(x, y):try:
result = x / y
except ZeroDivisionError:print("division by zero!")else:print("result is", result)finally:print("executing finally clause")divide(2,1)
result is 2.0
executing finally clause
 divide(2,0)
division by zero!
executing finally clause
 divide("2","1")
executing finally clause
Traceback(most recent call last):
File "<stdin ", line 1,in?
File "<stdin ", line 3,in divide
TypeError: unsupported operand type(s)for/:'str' and 'str'
Predefined cleanup behavior
Some objects define a standard cleanup behavior, regardless of whether the system successfully uses it, once it is no longer needed, then this standard cleanup behavior will be executed.

This example shows an attempt to open a file and then print the content to the screen:for line inopen("myfile.txt"):print(line, end="")
The problem with the above code is that when the execution is complete, the file will remain open and not closed.

The keyword with statement can ensure that objects such as files will be executed correctly after use.:withopen("myfile.txt")as f:for line in f:print(line, end="")
After the above code is executed, even if there is a problem in the processing, the file f will always be closed.

Python standard exception

Exception name Description
BaseException The base class of all exceptions
SystemExit Interpreter request to exit
KeyboardInterrupt User interrupt execution (usually input ^C)
Exception Base class for general errors
StopIteration Iterator has no more values
GeneratorExit An exception occurs in the generator to notify the exit
StandardError The base class for all built-in standard exceptions
ArithmeticError The base class for all numerical calculation errors
FloatingPointError Floating point calculation error
OverflowError Numerical operation exceeds the maximum limit
ZeroDivisionError Division (or modulo) zero (all data types)
AssertionError Assertion statement failed
AttributeError Object does not have this attribute
EOFError No built-in input, EOF mark reached
EnvironmentError Base class for operating system errors
IOError Input/output operation failed
OSError operating system error
WindowsError System call failed
ImportError Failed to import module/object
LookupError Base class for invalid data query
IndexError There is no such index in the sequence (index)
KeyError The key is not in the map
MemoryError Memory overflow error (not fatal to the Python interpreter)
NameError Object not declared/initialized (no attributes)
UnboundLocalError Access to uninitialized local variables
ReferenceError Weak reference attempts to access objects that have been garbage collected
RuntimeError General runtime error
NotImplementedError Method not yet implemented
SyntaxError Python syntax error
IndentationError Indentation Error
TabError Tab and spaces mixed
SystemError General interpreter system error
TypeError Invalid operation on type
ValueError Invalid parameter passed in
UnicodeError Unicode related errors
UnicodeDecodeError Unicode decoding error
UnicodeEncodeError Unicode encoding time error
UnicodeTranslateError Unicode conversion error
Warning The base class of warning
DeprecationWarning Warning about deprecated features
FutureWarning Warning about future semantic changes in the construction
OverflowWarning Old warning about automatic promotion to long integer
PendingDeprecationWarning Warning about the feature will be deprecated
RuntimeWarning Warning of suspicious runtime behavior
SyntaxWarning Suspicious Syntax Warning
UserWarning Warning generated by user code

Recommended Posts

Python&#39;s exception concept introduction and handling
Python exception handling
Ubuntu introduction and installation
Anaconda introduction and Ubuntu/windows installation Anaconda
Python&#39;s history, advantages and disadvantages
Python&#39;s global variables and local variables
Python common exception handling mechanism