(python) exception handling

1. What is an exception

    An exception is a signal that an error has occurred. Once an error occurs in the program, if there is no corresponding processing mechanism in the program, then the error will generate an exception and the program will be terminated.

    An exception is divided into three parts:


    1, is abnormal: tracking information

    2, is abnormal: type (class)

    3, is abnormal: value


2. Anomaly classification

1. Syntax exception:

Such exceptions should be corrected before program execution

2. Logical exception:

(The most common ones are as follows)

IndexError (out of index range)

KeyError (the key does not exist in the dictionary)

AttributeError (Accessing an attribute of an object that does not have this attribute. An attribute exception is generated)

IOError (input\output exception, usually the file cannot be opened)

ZeroDivisionError (eg 1/0)

FileNotFoundError (file does not exist)

TyepError (the incoming object type does not match the required type)

NameError (using an unassigned variable)

ValueError (pass in a value not expected by the caller, even if the type of the passed in value is OK)




3. Exception handling

try:
    print('start.....')
    a
    l=['a','b']
    l[6]
    d={'a':1}
    d['b']
    print('end......')
except NameError:
    print('variable is not defined')
except IndexError:
    print('Index out of range')
except KeyError:
    print('The key of the dictionary does not exist')

print('other')

The result is:


The above exception can also be roughly handled with a logic in the following figure


There is also a rough handling exception is the universal exception (Exception)


With universal exception handling, we do not know the specific name of the exception, but we already know that the exception is divided into three parts. We can assign the value of this exception to a variable to determine what kind of exception it is.

try:
    print('start....')
    import them
    os.aaa
    a
    l=['a','b']
    l[6]
    d={'a':1}
    d['b']
    print('end......')
except Exception as e :
    print('Universal exception---"',e)

print('other....')

The result is:


At this time, we can infer that it is an AttributeError by the value of the obtained exception.

You can also take out an exception to deal with separately, and deal with other exceptions roughly. :



try...excpt....else....finally handling exception usage:

else : must be used with except, meaning: the code block in else will be executed without exception.


finally : The finally block will be executed with or without exception! ! !


Look at the following code to use finally to recycle resources,

try:
    f=open('a.txt',mode='w',encoding='utf-8')
    f.readline()
    f.close()
except Exception as e:
    print (s)
        The above code reads the code with an exception, but the file is already open, and the file is not closed after the exception is thrown, so we have to make it close the file resource after execution regardless of whether there is an exception.

So the above code needs to be modified as follows:

try:
    f=open('a.txt',mode='w',encoding='utf-8')
    f.readline()

except Exception as e:
    print (s)
finally:
    f.close()

Actively trigger an exception:


class People:
    def __init__(self,name):
        self.name=name
        if not isinstance(name,str):
            raise TypeError('%s must be str type'%name)

        self.name=name
p=People(123)

The result is shown as:



4. Assertion


Five, custom exception

class RegisterError(BaseException):
    def __init__(self,msg,user):
        self.msg=msg
        self.user=user
    def __str__(self):
        return '<%s,%s>'%(self.user,self.msg)

# raise RegisterError('Registration failed','teacher')
obj=RegisterError('Registration failed','teacher')
print(obj)

Finally when do we use exception handling! ! !

        When the error conditions are predictable, don't make exception handling and use if conditions to prevent errors before they occur. But there are a lot of exceptions we can't predict, so we need to catch exception handling.

Summarize:

        Catching exceptions (try...execpt), it separates error handling from the actual code to run, the code is more organized, the code runs more safely, and does not crash due to some small error.

Guess you like

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