20. Exception Handling

exception handling

What is an exception?

after exception

The code after the exception is not executed

what is exception handling

The python interpreter detects an error and triggers an exception (also allows programmers to trigger exceptions themselves)

The programmer writes specific code specifically to catch this exception (this code has nothing to do with program logic, but with exception handling)

If the capture is successful, enter another processing branch, execute the logic you customized for it, so that the program will not crash, this is exception handling

Why do you need exception handling?

The python parser executes the program. When an error is detected, an exception is triggered. After the exception is triggered and not handled, the program is terminated at the current exception, and the following code will not run. software that crashes.

So you must provide an exception handling mechanism to enhance the robustness and fault tolerance of your program 

How to handle exceptions?

First of all, it should be noted that exceptions are caused by program errors. Syntax errors have nothing to do with exception handling and must be corrected before the program runs.

One: use if judgment

normal code
Exception handling using if judgment

Summarize:

1. The if-judgmental exception handling can only be used for a certain piece of code. For the same type of error in different code segments, you need to write repeated if to handle it.

2. Frequently writing in your program has nothing to do with the program itself, if related to exception handling, will make your code readability extremely poor

3. if can solve exceptions, but there are problems 1 and 2, so don't jump to the conclusion that if can't be used for exception handling.

Some common types of errors
AttributeError attempting to access a tree that an object does not have, such as foo.x, but foo has no attribute x
IOError input/ output exception; basically the file cannot be opened ImportError cannot import module or package; basically path problem or wrong name IndentationError syntax error (subclass of); code is not properly aligned IndexError The subscript index exceeds the sequence boundary, such as trying to access x[5 ] when x has only three elements KeyError attempting to access a key that does not exist in the dictionary KeyboardInterrupt Ctrl+ C is pressed NameError Using a variable that has not been assigned to an object SyntaxError Python code is illegal, the code cannot be compiled (personally think this is a syntax error, wrongly written) TypeError The incoming object type does not meet the requirements UnboundLocalError Attempt to access a A local variable that has not been set, basically because there is another global variable with the same name, leading you to think you are accessing it ValueError passing in a value that the caller does not expect, even if the value is of the correct type

One: use if judgment

 

num1=input( ' >>: ') # try to enter a string int(num1)
 

copy code
num1=input( ' >>: ') #Enter a string and try if num1.isdigit(): int(num1) #Our orthodox program is put here, and the rest belong to the category of exception handling elif num1.isspace() : print( ' If the input is a space, execute my logic here ' ) elif len(num1) == 0: print( ' If the input is empty, execute my logic here ' ) else : print( ' Other situations , Execute my logic here ' ) ''' Question 1: We only add exception handling to the first piece of code by using if, but these ifs have nothing to do with your code logic, so your code will Poor readability and not easy to understand Problem 2: This is just a small logic in our code. If there are many similar logics, then we need to judge these contents every time, and our code will be inverted and extremely verbose. '''
copy code
 

Summarize:

 

1. The if-judgmental exception handling can only be used for a certain piece of code. For the same type of error in different code segments, you need to write repeated if to handle it.

 

2. Frequently writing in your program has nothing to do with the program itself, if related to exception handling, will make your code readability extremely poor

 

3. if can solve exceptions, but there are problems 1 and 2, so don't jump to the conclusion that if can't be used for exception handling.

 
copy code
def test():
     print( ' test running ' ) choice_dic= { ' 1 ' :test } while True: choice=input( ' >>: ' ).strip() if not choice or choice not in choice_dic: continue #this It is an exception handling mechanism, choice_dic[choice]()
copy code
 

Two: python customizes a type for each exception, and then provides a specific grammatical structure for exception handling

 

part1: Basic syntax

 
try:
     Checked code block
except exception type: Once an exception is detected in try, the logic at this position is executed
 
copy code
f = open('a.txt')
 g = (line.strip() for line in f) for line in g: print(line) else: f.close()
copy code
 
copy code
try:
    f = open( ' a.txt ' ) g = (line.strip() for line in f) print (next(g)) print (next(g)) print (next(g)) print (next(g) ) print (next(g)) except StopIteration: f.close() ''' next(g) will trigger iteration f, and then next(g) can read the contents of the file line by line, no matter how big the file a.txt is , there is only one line of content in memory at the same time. Tip: g exists based on the file handle f, so f.close() can only be executed after next(g) throws an exception StopIteration '''
copy code
 

part2: The exception class can only be used to handle the specified exception, and it cannot be handled if the exception is not specified.

 
 

 
s1 = 'hello' try: int(s1) except IndexError as e: print e
In this case , an error will be reported when other types of exceptions are encountered, unless you are sure that it must be this type of error, then use it.
 

part3: Multi-branch

 
copy code
s1 = 'hello'
try: int(s1)
except IndexError as e: print(e) except KeyError as e: print(e) except ValueError as e: print(e)
copy code
 

part4: Universal exception In python's exceptions, there is a universal exception: Exception, which can catch any exception, namely:

 
s1 = 'hello'
try: int(s1)
except Exception as e: print(e)
 

You may say that since there are universal exceptions, then I can just use the above form, and other exceptions can be ignored

 

You are right, but it should be seen in two cases

 

1. If the effect you want is to discard any exceptions, or use the same piece of code logic to deal with them, then Sao Nian, do it boldly, only one Exception is enough.

 
s1 = 'hello'
try: int(s1)
except Exception,e: ' Discard or execute other logic ' print (e) #If you use Exception uniformly, yes, you can catch all exceptions, but it means that you use the same logic to handle all exceptions (here The logic mentioned is the code block following the current expect)
 

2. If the effect you want is that we need to customize different processing logic for different exceptions, then you need to use multiple branches.

 
s1 = 'hello'
try: int(s1)
except IndexError as e: print(e) except KeyError as e: print(e) except ValueError as e: print(e) except Exception as e: print(e)
For multi-branch, we will also add a universal exception at the end, just in case.
 
copy code
s1 = 'hello'
try: int(s1)
except IndexError as e: print(e) except KeyError as e: print(e) except ValueError as e: print(e) except Exception as e: print(e)
copy code
 

part5: Abnormal Other Institutions

 
copy code
s1 = 'hello'
try: int(s1)
except IndexError as e: print (e) except KeyError as e: print (e) except ValueError as e: print (e) # except Exception as e: # print(e) else : print( ' If there is no exception in the code block in try Execute me ' ) finally : print( ' Whether there is an exception or not, the module will be executed, usually to clean up ') 
When else and finally are used together, if there is no exception in the code, execute the code in else, if there is any It will not be executed, but the finally code will definitely be executed.
copy code
 

part6: Actively trigger exceptions

 
try :
     raise TypeError( ' type error ' ) except Exception as e: print(e) 
takes the initiative to initiate an exception. There are two most commonly used places: 1. In the campus management system, when the user is asked to select the serial number, when the user When you enter 0, you can't judge by exception handling at this time, because when you enter 0,
the item with the serial number of -1 in the list will be selected, which is the last item in the list to execute, so when the user enters 0, we It is necessary to actively throw exceptions

. 2. In the normalized design of object-oriented, if there is no set method name, an exception can be thrown.
 

part7: custom exception

 
copy code
class EvaException(BaseException):
    def __init__(self,msg): self.msg=msg def __str__(self): return self.msg try: raise EvaException('类型错误') except EvaException as e: print(e)
copy code
 

part8: Assertion

 
# assert condition
 
assert 1 == 1
 
assert 1 == 2
 

Part9: The advantages of the try..except method compared to the if method

 

The exception handling mechanism of try..except is to replace the if method, making your program more robust and fault-tolerant without sacrificing readability

 

The exception type is customized for each exception in exception handling (the class and type are unified in python, and the type is the class). For the same exception, one except can catch it, and can handle the exceptions of multiple pieces of code at the same time (no need to write multiple if judgment type') reduces code and enhances readability 

 

 

 

The way to use try..except

 

1: Separate error handling from real work
2: Code is easier to organize, clearer, and complex tasks are easier to implement;
3: Undoubtedly, it's safer to not accidentally crash the program due to some small oversight ;

 

 

 
 
 

When to use exception handling

 

Some students will think this way. After learning exception handling, it is very powerful. I will add try...except to each of my programs, and think about whether it will have logical errors. This is very good. Ah, save more brain cells ===> 2B youths are more happy

 

try ...except should be used as little as possible, because it itself is an exception handling logic that you attach to your program. If you
add too much of this kind of thing that has nothing to do with your main work, it will cause you The readability of the code becomes worse, try...except should be added only when some exceptions are unpredictable, and other logic errors should be corrected as much as possible

 
 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325130123&siteId=291194637