Participation in the award: This article has participated in the "Newcomer Creation Ceremony" activity, together with the start of the road of gold digging creationCopy the code
1. Exception handling

(1) Exception refers to the error caused by the program running, you can use the exception processing structure to improve the robustness and fault tolerance of the program; It can also provide more user-friendly prompts for users;

② Note: programming should avoid relying too much on exception handling mechanisms to improve program robustness;

③ Note: If the exception is not caught or appears in an else/finally block, it will be thrown after the finally statement;

2. Code demonstration:

① Implement error handling of custom classes by inheriting Python’s built-in exception classes

class myError(Exception) :
    "Custom Exception Class"
    def __init__(self,length,atleast) :
        Exception.__init__(self)    Call the parent constructor
        self.length=length
        self.atleast=atleast
Use the try statement block to detect exceptions
try:
    s=input('Please enter a string:')
    if len(s)<3:
        raise myError(len(s),3) Throw a possible exception statement
except EOFError:        # catch exception
    print('You entered an end flag (EOF)! ')
except myError as x:
    print('myError: Enter length %d, length should be at least: %d' %(x.length,x.atleast))
else:
    print('No exception caught! ')        
Copy the code

The results are as follows:

Please enter a string:12MyError: The input length is2, the length should be at least:3
Copy the code

② Similar to case ①

class myError1(Exception) :
    def __init__(self,value) :
        self.value=value
    def __str__(self) :
        return repr(self.value)
try:
    raise myError1(2*2)
except myError1 as x:
    print('My exception occurred,value:',x.value)
#raise myError1('hello')
Copy the code

③ A module containing multiple except blocks

class myError2(Exception) :  Inherit Pytho's exception class
    pass
class myError3(myError2) :   # Inherit parent class
    def __init__(self,expression,message) :
        self.expression=expression
        self.message=message
class myError4(myError2) :   # Inherit parent class
    def __init__(self,previous,next,message) :
        self.previous=previous
        self.next=next
        self.message=message
Copy the code

Detection statement:

try:
    s1=input('Please enter 1:')
    s2=input('Please enter 2:')
    s3=input('Please enter 3:')
    if len(s1)>0 and len(s2)>0 and len(s3)==0:
        raise myError3(s1,s2)
    elif len(s1)>0 and len(s2)>0 and len(s3)>0:
        raise  myError4(s1,s2,s3)
except EOFError:
    print(You entered an end flag (EOF)! ')
except myError3 as x:
    print('Expression :%s,message:%s'%(x.expression,x.message))
except myError4 as x:
    print('Entered three messages! ')
else:
    print('No exception! ')
Copy the code
3. Abnormal processing structure analysis

1) try… except

# until the user enters data as a number to end the loop
while True:
    try:
        x=int(input('Please input a number:'))
        break
    except ValueError:
        print('Input type error! ')
Copy the code

(2) the try… except… except…

# try structure with multiple except statements
try:
    i=float(input('Dividend:'))
    i1=float(input('Divisor:'))
    z=i/i1
except ValueError:
    print('Value type is value! ')
except ZeroDivisionError:
    print('Divisor cannot be 0! ')
except TypeError:
    print('Both data types should be numeric! ')
except NameError:
    print('Variable does not exist! ')
else:
    print(i,'/',i1,'=',z)
Copy the code

(3) the try… except():

It is possible to use tuples to catch multiple exceptions in a single statement
import sys
import os
try:
    f=open('1.txt'.'r+')
    s=f.readline()
    #print(s,end='\n')
    i=int(s.strip())
    #print(i,end='\n')
except (OSError,ValueError,RuntimeError,NameError):
    pass
Copy the code

(4) the try… except… Finally (Executes regardless of whether an exception is thrown or not)

try:
    3/0
except:
    print(3)
finally:
    print(5)
Copy the code

Output result:

3
5
Copy the code

5. Pay attention!

# Note: If the exception is not caught or appears in an else/finally block, it is thrown after the finally statement
def divide(x,y) :
    try:
        result=x/y
    except ZeroDivisionError:
        print('division is zero! ',end='\n')
    else:
        print(x,'/',y,'=',result,end='\n')
    finally:
        print('executing finally clause',end='\n')
divide(1.2)
divide(1.0)
divide("2"."1")
Copy the code

Output result:

1 / 2 = 0.5
executing finally clause
division is zero!
executing finally clause
executing finally clause
    result=x/y
TypeError: unsupported operand type(s) for/ :'str' and 'str'
Copy the code

6. Pay attention! Try to avoid using return statements in exception handling modules that contain finally blocks!

Learning notes

1. There are many causes of program running errors. Strictly speaking, syntax errors and logical errors do not belong to exceptions;

2. Exception mechanisms are very important and effective, but it is not recommended to use exception mechanisms in place of routine checks;

3. Avoid relying too much on exception handling mechanism to improve program robustness in the programming process;

4. The exception handling structures in Python are

try… except;

try… except… else;

try… except… except…. ;

try… except… finally… ;

try… except… else… finally… And other combinations;

5. You can inherit Python’s native Exception handling class, Exception