And other languages, Python exception handling is a very important mechanism and code specifications.
I. errors and exceptions
Generally bugs in the program is divided into two, one is a syntax error, the other is abnormal. We must first understand the difference between errors and exceptions and links.
Syntax errors easier to understand, is to write code that does not conform to become standardized, it can not be recognized or executed, like this
>>> print(name) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'name' is not defined
As the name of this variable is not declared before it is called, it will error when called. Or if the statement is missing after the colon, indentation errors and so on.
The anomaly refers to the program can be executed properly, but in the implementation process will encounter an error and then throw an exception, such as this
>>> l = [1,2,3] >>> l + 2 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can only concatenate list (not "int") to list >>> 10/0 Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDivisionError: division by zero >>> dic = {'name':'123'} >>> dic['age'] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'age'
Examples of the above three exception occurred, namely, the type of error, the divisor can not be 0 and the dictionary key error. There are many, many types of anomalies, the other can query the exception of official documents .
II. Handle exceptions
If the program execution to go somewhere exception, the program will terminate and exit, and sometimes we did not want the program to stop, this time we should use exception handling , and usually try to achieve and except. Like this:
while True: a = input('a:') b = input('b:') try: a = float(a) b = float(b) print('a/b={}'.format(a/b)) except ZeroDivisionError as e: print(e)
Thus when the input b is 0, the program will print out and thrown
a:1
b:0
float division by zero
However, except block and listed catch only exception types of abnormality match, when the input of a or b is non-numeric strings, or after the given program terminates and exits.
A: A B: 2 Traceback (MOST Recent Last Call): File " D: / Python / core technology combat the Python / exception handling .py " , Line. 6, in <Module1> A = a float (A) a ValueError: Could Not Convert to a float String: ' A '
There are two solutions, one is the wait may appear abnormal to make two kinds of exceptions are listed, such as this
while True: a = input('a:') b = input('b:') try: a = float(a) b = float(b) print('a/b={}'.format(a/b)) except (ZeroDivisionError,ValueError) as err: print(err)
Or write separately
while True: a = input('a:') b = input('b:') try: a = float(a) b = float(b) print('a/b={}'.format(a/b)) except ZeroDivisionError as err: print('ZeroDivisionError:{}'.format(err)) except ValueError as err: print('ValueError:{}'.format(err))
Thus, when the program is executed, except block as long as there is an exception type can be matched with actual.
But most of the time it is difficult to ensure that the program can cover all types of exceptions, so it is common practice to add a last exception type except block, declared Exception. Exception system exceptions are all non base class, all non-matching can be abnormal chest. So the code should look like this
while True: a = input('a:') b = input('b:') try: a = float(a) b = float(b) print('a/b={}'.format(a/b)) except ZeroDivisionError as err: print('ZeroDivisionError:{}'.format(err)) except ValueError as err: print('ValueError:{}'.format(err)) except Exception as err: print('Other error:{}'.format(err))
Or omit the exception type behind except, represents any abnormality match (including system abnormality).
except: print('Other error')
Here is a point to note: If there is more except block the program, can only be made a catch block ,, meaning that only the front of the block is executed, the latter is ignored.
Three .finally usage
As well as exception handling one of the most commonly used method is finally, it often and try, except used together, no matter what happened earlier, the statement will be executed in the finally block. Even by the foregoing block return . A common scenario is reading operation of the document
try: f = open('file.txt','r') except OSError as err: print(err) except: print('Unexpected error') finally: f.close()
No matter what operation to perform in front of, the last is to close the file, to ensure the integrity of the file. So, finally, we will put some statements executed anyway . In fact, for the example above, the operation of the file in front of the usage is with open grammar, and finally automatically closes the file with open make the code look cleaner.
IV. User-defined exceptions
The above example has been cited in several Python built-in exception types are also given an official document. In fact, we can also define your own exception types
class MyInputError (Exception): DEF the __init__ (Self, value): self.value = value DEF __str__ (Self): # from the abnormal expression defined string return ( ' {} invalid INPUT IS ' .format (the repr (self.value ))) the try : The raise MyInputError (123) # directly thrown the except MyInputError AS ERR: Print ( ' error: {} ' .format (ERR))
Here we also used to raise direct throw. In fact, the kind of Python's built-in exceptions generally speaking have been enough! Normally users do not need to define your own!
V. abnormal usage scenarios and Precautions
We want to focus on in this section look abnormal usage scenarios and attention points:
Generally speaking, we are not sure if a piece of code execution success, often there will need to add exception handling example, we acquired a key-value data structure from the database, this kind of data in general is through the website background after a string of json serialization, we want to get the data you need to string decode.
Import json raw_data = queryDB (UID) # acquires character string data json serialized data = json.loads (raw_data)
In json.loads () function if the input string does not meet its specifications, can not be decoded, the program will throw an exception, this time adding exception handling is very important.
But we have to avoid the other extreme: the abuse of exception handling
data = {'name':'jack', 'age':22} try: data['job'] except KeyError as err: print('KeyError:{}'.format(err))
This code is actually no problem, but appears to have redundancy, so people generally do not use. So use it directly
if 'job' in data: data['job']
More simple, direct write
data.get('job')
Therefore, the general flow-control (flow control) of the code logic, we generally do exception handling .