The Road to Programming: Exception Handling

what is an exception

An exception is a signal that an error occurs when the program is running (when an error occurs in the program, an exception will be generated, and if the program does not handle it, it will be thrown.

exception, the operation of the program is also terminated), in python, the exception triggered by the error is as follows

Errors are divided into two

#Syntax error example 1 
if 
#Syntax error example 2 
def test:
     pass #Syntax 
error example 3 
class Foo
     pass #Syntax 
error example 4 
print (haha
1. Syntax error (this kind of error cannot pass the syntax detection of the python interpreter and must be corrected before the program is executed)
# TypeError: int type is not iterable 
for i in 3 :
     pass 
# ValueError 
num=input( " >>: " ) #input hello int(num )


# NameError 
aaa

#IndexError
l=['egon','aa']
l[3]

#KeyError
dic={'name':'egon'}
dic['age']

#AttributeError
class Foo:pass
Foo.x

# ZeroDivisionError: Could not complete calculation 
res1=1/ 0
res2 = 1 + ' str '

2. Logic Error
2. Logic Error

 

kind of exception

Different exceptions in python can be identified by different types (classes and types are unified in python, and types are classes), and an exception identifies an error

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, written wrong)
TypeError The incoming object type does not meet the requirements
UnboundLocalError attempts to access a local variable that has not been set, basically because there is another global variable with the same name,
cause you to think you are accessing it
ValueError passes in a value not expected by the caller, even if the value is of the correct type

Common exception
Common exception
ArithmeticError
AssertionError
AttributeError
BaseException
BufferError
BytesWarning
DeprecationWarning
EnvironmentError
EOFError
Exception
FloatingPointError
FutureWarning
GeneratorExit
ImportError
ImportWarning
IndentationError
IndexError
IOError
KeyboardInterrupt
KeyError
LookupError
MemoryError
NameError
NotImplementedError
OSError
OverflowError
PendingDeprecationWarning
ReferenceError
RuntimeError
RuntimeWarning
StandardError
StopIteration
SyntaxError
SyntaxWarning
SystemError
SystemExit
TabError
TypeError
UnboundLocalError
UnicodeDecodeError
UnicodeEncodeError
UnicodeError
UnicodeTranslateError
UnicodeWarning
UserWarning
ValueError
Warning
ZeroDivisionError

more exceptions
more exceptions

exception handling

In order to ensure the robustness and fault tolerance of the program, that is, the program will not crash when encountering an error, we need to handle the exception,

If the conditions under which the error occurs are predictable, we need to handle it with if: prevent errors before they occur

AGE=10
while True:
    age =input( ' >>: ' ).strip()
     if age.isdigit(): #Only when age is an integer in the form of a string, the following code will not error, the condition is predictable 
        age= int( age)
         if age == AGE:
             print ( ' you got it ' )
             break
View Code

 

If the conditions under which the error occurs are unpredictable, try...except: to handle the error after it occurs

#The basic syntax is 
try :
    Checked code block
except exception type:
    Once an exception is detected in try, the logic at this position is executed
#Example 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()
# 1 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: #Uncaught exception , the program reports an error directly 
    print e

# 2 
Multibranch s1 = ' hello ' 
try :
    int(s1)
except IndexError as e:
    print(e)
except KeyError as e:
    print(e)
except ValueError as e:
    print(e)

# 3 Universal exception Exception 
s1 = ' hello ' 
try :
    int(s1)
except Exception as e:
    print(e)

# 4 Multi-branch exceptions and universal exceptions 
# 4.1 If the effect you want is that no matter what exceptions occur, we discard them uniformly, or use the same piece of code logic to deal with them, then Sao Nian, do it boldly, there is only one Exception Will suffice. 
# 4.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.

# 5 can also be followed by an Exception after multibranch 
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)

# 6 Exception for other bodies 
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 ( ' regardless of exception or not, the module will be executed, usually for cleanup work ' )

# 7 Actively trigger exception 
try :
     raise TypeError( ' type error ' )
 except Exception as e:
     print (e)

# 8 Custom exception 
class EgonException(BaseException):
     def  __init__ (self,msg):
        self.msg=msg
    def __str__(self):
        return self.msg

try :
     raise EgonException( ' type error ' )
 except EgonException as e:
     print (e)

# 9 assert: assert condition 
assert 1 == 1  
 assert 1 == 2

# 10 Summary try..except

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

When to use exception handling

First of all, try...except is an exception handling logic that you attach to your program. It has nothing to do with your main work. Adding too much of this will make your code less readable.

Try...except should only be added if the conditions under which the error occurs are unpredictable

 

 

 

Guess you like

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