Exceptions and Errors
One: Syntax error (this error, the syntax of the Python interpreter cannot be detected, must be corrected before the program executes)
# Syntax error demonstration one if# syntax error demonstration two defPass# syntax error demo three print (haha
Two: Logic error
# The user input is incomplete (for example, the input is empty) or the input is illegal (input is not a number) Num=input ("") int (num)# cannot complete the calculation res1=1/0res2=1+' str'
What is an exception
An exception is a signal that an error occurs while the program is running, and in Python the exception that is triggered by the error is as follows
Types of exceptions in Python
Different exceptions in Python can be identified in different types (Python unifies classes and types, types as classes), non -identical class objects identify different exceptions, an exception identifies an error
l=['Egon ','aa']l[3]
dic={'name':'Egon'}dic['age']
s='Hello'int (s)
Common exceptions
Exception handling
After an exception occurs
The code after the exception is not executed.
The Python interpreter detects an error, triggering an exception (also allowing the programmer to trigger an exception himself)
Programmers write specific code that is specifically designed to catch this exception (this code is independent of the program logic and is related to exception handling)
If the capture succeeds, go to another processing branch, execute the logic you've customized for it, and the program won't crash, which is exception handling
Why do you want to do exception handling?
The Python parser goes to execute the program, detects an error, triggers an exception, the exception is triggered and is not processed, the program terminates at the current exception, and the code behind it does not run, who will use a software that is running with a sudden crash.
So you have to provide an exception handling mechanism to enhance the robustness and fault tolerance of your program.
How do I do exception handling?
First of all, the exception is caused by a program error, grammatical errors are not related to exception handling, must be corrected before the program runs
One: Using the IF-judgment
Num1=input ('# Enter a string to try Int (NUM1)
#_*_coding:utf-8_*___author__ =‘Linhaifeng‘Num1=input (‘>>:‘)#Enter a string to tryIfNum1.isdigit (): Int (NUM1)#Our Orthodox program is here, and the rest belongs to the exception-handling category.ElifNum1.isspace ():Print " Enter a space and execute my logic here " ) elif len (NUM1) == 0: print ( ' The input is empty, just execute my logic ' ) else: Span style= "COLOR: #0000ff" >print ( " Other situation, execute my logic here ' ) question one: Using the If method we only add exception handling for the first piece of code, but these if are not related to your code logic, This way your code will not be easy to read because of poor readability. Second: This is just a small logic in our code, if the logic is much like, then every time we need to judge the content, it will be inverted our code is very verbose.
Summarize:
1.if-Judging exception handling can only be done for a piece of code, for the same type of error for different pieces of code you need to write the duplicate if to handle it.
2. Frequent writes in your program are not related to the program itself, and if it is related to exception handling, it will make your code very readable.
3.if is able to solve the anomaly, but there are problems, so do not jump to the conclusion that if can not be used for exception handling.
How you handled the exception handling before
DefTest ():Print ' test running ") choice_dic={1 ":test}while True:choice=input (" >>: ' ). Strip () if not choice or choice not in choice_dic: Continue # This is an exception handling mechanism AH Choice_dic[choice] ()
Two: Python customizes a type for each exception, and then provides a specific syntax structure for exception handling
part1: Basic Syntax
Try: code block except exception type: When an exception is detected in try, the logic for this position is executed
f = open ('a.txt'in f)inprint(line)else: F.close ()
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 an iteration F, and next (g) will be able to read a line of the file. No matter how big the file A.txt, there is only one line of content in memory at the same time. Tip: G is based on file handle F and can only be executed after next (g) throws an exception stopiteration F.close ()
Part2: The exception class can only be used to handle the specified exception condition and cannot be processed if a non-specified exception occurs.
# no exception caught, program directly error 'Hello'try: Int (s1)exceptprint e
part3: Multi-branch
'Hello'try: int (s1)exceptprint(e)exceptprint(e)except Print (e)
PART4: Universal exception in Python's exception, there is a universal exception: Exception, he can catch arbitrary exceptions, namely:
'Hello'try: int (s1)exceptprint (e)
You may say that since there is a universal exception, then I use the above form directly, other exceptions can be ignored
You're right, but you should see it in two different ways.
1. If the effect you want is, no matter what happens, we discard uniformly, or use the same piece of code logic to deal with them, then the year, bold to do it, only one exception is enough.
'Hello'try: int (s1)except' discard or perform other logical print(e)# If you use exception uniformly, yes, you can catch all exceptions, but that means you use the same logic to handle all exceptions (the logic here is the block of code that is followed by the current expect)
2. If the effect you want is that we need to customize different processing logic for different exceptions, we 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)
'Hello'try: int (s1)exceptprint(e)exceptprint(e)except Print(e)exceptprint (e)
Part5: Exception of other institutions
S1 =‘Hello‘Try: Int (S1)ExceptIndexerror as E:Print(e)ExceptKeyerror as E:print (e) except ValueError as E: print (E) #except Exception as E:# print (e) else: print (" try within the code block no exception to execute my ' ) finally: print (" The module executes whether it is unusual or not, usually for cleanup work
part6: Active triggering exception
Try: raise TypeError (' type error ')exceptprint (e)
PART7: Custom exception
ClassEvaexception (baseexception): def __init__(self,msg): self.msg=msg def __str__(self): return self.msgtry: raise Evaexception (' type error ')except Evaexception as E: print (e)
PART8: Assertion
#Assert 1 = = 2
Part9:try. Except ways to compare the benefits of the IF way
Try: Except this exception handling mechanism is to replace if that way, allowing your program to enhance robustness and fault tolerance without sacrificing readability
Exception types are customized for each exception (Python unifies classes and types, type is a Class), and for the same exception, a except can be caught, an exception that can handle multiple pieces of code at the same time (without ' writing multiple if judgments ') reduces code and enhances readability
Use try: The way of except
1: Separate the error handling from the real work
2: Code easier to organize, clearer, complex tasks easier to implement;
3: No doubt, more secure, not due to some small negligence to make the program accidentally collapsed;
When to use exception handling
Some students will think so, after learning the exception processing, good strong, I want to each of my procedures are added try...except, dry wool to think it will have logic error Ah, this is very good ah, multi-province brain cell = = = 2B Youth Happy Many
Try...except should be used sparingly, because it is an exception-handling logic that you attach to your program, which is not related to your main work.
This kind of thing adds more, will cause your code readability to be poor, only if some exception is unpredictable, should add try...except, other logic error should try to correct
python--Exception Handling