One 、 What is an anomaly

 

Python Errors and exceptions

What is an anomaly

> An exception is an event , This event occurs during program execution , Affect the normal execution of the program . In general , stay Python An exception occurs when the program cannot be handled properly . Exception is Python The object of , A mistake . When Python When a script exception occurs , We need to catch and handle exceptions , Otherwise, the program will terminate .

> Every exception is an instance of some class , These instances can be referenced , And it can be captured in many ways , So that errors can be handled , Instead of letting the whole program fail .

There are a lot of exceptions in the code , such as NameError Name error ,Syntax Error Grammatical anomalies ,Type Error Type error ,Value Error Value anomaly ; All four are abnormal , An exception is actually an event

It's very normal to have exceptions in the code , Exception caught , Just throw it away

>>> 10*(1/0)

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

ZeroDivisionError: division by zero

>>> 4+a1*3

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

NameError: name 'a1' is not defined

>>> '2'+2

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: can only concatenate str (not "int") to str

These are called anomalies

 

Two 、 exception handling

 

exception handling

> try The basic form of the sentence is try/except.try/except Statement is used to detect try Error in statement block , So that except Statement to capture exception information and handle . If you don't want to end the program when something goes wrong , Just in try Statement block can catch exception .

> The syntax for catching exceptions is as follows :

> Exception capture try/except

1-1def exp_exception(x,y):try:
        a=x/yprint('a=',a)return aexcept Exception:print(" Program exception , Abnormal information : The divisor is 0")
 
exp_exception(2,2)=>a= 1.0
1-2def exp_exception(x,y):try:
        a=x/yprint('a=',a)return aexcept Exception:print(" Program exception , Abnormal information : The divisor is 0")
 
exp_exception(2,0)=> Program exception , Abnormal information : The divisor is 0

 

> Catch multiple exceptions

1-1def exp_exception(x,y):try:
        a=x/y
        b=nameprint('a=',a)return aexcept ZeroDivisionError:print(" The divisor cannot be zero 0")except NameError:print(" There's no name you're looking for ")
 
exp_exception(2,0)=> The divisor cannot be zero 0
1-2def exp_exception(x,y):try:
        a=x/y
        b=nameprint('a=',a)return aexcept ZeroDivisionError:print(" The divisor cannot be zero 0")except NameError:print(" There's no name you're looking for ")
 
exp_exception(2,2)=> There's no name you're looking for 

 

> Use one block to catch multiple exceptions

> If you need to use a block to catch multiple types of exceptions , You can list them as tuples . When using this method , The exception type encountered is any of the tuples , Will go through the abnormal process .

> What are the benefits of doing so ? If we want more except Clause outputs the same information , There's no need to be in a few except Repeat input statement in clause , Just put it in an exception block .

Just used except Two exceptions were caught , Now I want to write two exceptions to one except in

def exp_exception(x,y):try:
        a=x/y
        b=nameprint('a=',a)return aexcept (ZeroDivisionError,NameError,TypeError):print(" Your output is wrong !")
 
exp_exception(2,'0')=> Your output is wrong !

 

exception handling

> Capture objects

> If you want to except Clause to access the exception object itself , That is to see the real exception information of an exception object , Instead of outputting self-defined exception information , have access to as e In the form of , We call it catching objects .

def exp_exception(x,y):try:
        a=x/y
        b=nameprint('a=',a)return aexcept (ZeroDivisionError,NameError,TypeError) as e:print(e)    #  Output  e, Don't write your own custom content here  exp_exception(2,'0')
exp_exception(2,0)
exp_exception(2,2)=>unsupported operand type(s) for /: 'int' and 'str'division by zero
name 'name' is not defined

That's how to capture objects , The previous exception prompt is custom , What the capture system means is to prompt the system to , use as e that will do

It's easier to locate than the system prompts

 

> Full capture

> In the actual coding process , Even if the program can handle several types of exceptions , But there are still some anomalies that slip out of our hands . There's no way we can predict what's going to happen in this situation , There's no way to prepare in advance . under these circumstances , Instead of using it to catch exceptions try/except Statement hides the exception , Let the program crash immediately .

def exp_exception(x,y):try:
        a=x/y
        b=nameexcept (ZeroDivisionError,NameError,TypeError) as e:print(e)   
 
exp_exception(2,'')=>unsupported operand type(s) for /: 'int' and 'str'

such b=name He ran away with his abnormality , No, right b Inspection

In this case , There's no way to predict what's going to happen in the future , There's no way to prepare ahead of time , So defects are bound to happen , So it's better to let the exception crash directly , Just write nothing at the back

def exp_exception(x,y):try:
        a=x/y
        b=nameexcept:print("Error")   
 
exp_exception(2,'')=>Error

It's called full capture if you don't write anything at the back , Of course, it's just a solution , This is not recommended from a practical point of view , Because it's very dangerous to catch anomalies in this way , Will hide all unexpected mistakes

 

> try/except...else

> try/except There is also an optional else Clause , If you use this clause , Then it must be put on all except After Clause .

> else Clause will be try Clause is executed when no exception occurs .

> try/except...else

def exp_exception(x,y):try:
        a=x/yexcept:print("Error")   else:print(" There are no errors in the program , end of execution ")
 
exp_exception(2,'')
exp_exception(2,2)=>Error

There are no errors in the program , end of execution

When there is no exception in the program , Will execute else Clause flow

 

> try-finally sentence

> try-finally Statement will execute the last code whether or not an exception occurs .

> There is finally In the exception handler of ,finally The clause in must be last executed .finally Clause is very useful when closing a file or database connection

If there is any abnormality ,try => except => finally

If there is no abnormality ,try => else => finally

def use_finally(x,y):try:
        a=x/yfinally:print(" No matter whether there is any abnormality or not , Will carry out my oh ~")
 
use_finally(2,2)
use_finally(2,0)=> No matter whether there is any abnormality or not , Will carry out my oh ~ No matter whether there is any abnormality or not , Will carry out my oh ~Traceback (most recent call last):
 File "d:/VSCode/Untitled-1.py", line 10, in <module>
 use_finally(2,0)
 File "d:/VSCode/Untitled-1.py", line 5, in use_finally
 a=x/y
ZeroDivisionError: division by zero

But this raises a new problem , Although the implementation of finally sentence , But the exception was thrown

Can you use except stay try There is no doubt about it

def use_finally(x,y):try:
        a=x/yexcept ZeroDivisionError:print(" The divisor cannot be zero 0")finally:print(" No matter whether there is any abnormality or not , Will carry out my oh ~")
 
use_finally(2,2)
use_finally(2,0)=> No matter whether there is any abnormality or not , Will carry out my oh ~ The divisor cannot be zero 0
No matter whether there is any abnormality or not , Will carry out my oh ~

Now add else It's the same

def use_finally(x,y):try:
        a=x/yexcept ZeroDivisionError:print(" The divisor cannot be zero 0")else:print(" Program executed successfully ")finally:print(" No matter whether there is any abnormality or not , Will carry out my oh ~")
 
use_finally(2,2)
use_finally(2,0)=> Program executed successfully
No matter whether there is any abnormality or not , Will carry out my oh ~ The divisor cannot be zero 0
No matter whether there is any abnormality or not , Will carry out my oh ~

except try, hinder except else and finally They are all called try Clause of , It has to be with try It makes sense to use it together

 

3、 ... and 、 Throw an exception

 

Throw an exception

> Python Use raise Statement throws a specified exception .

> raise The syntax is as follows :

I've been talking about catching exceptions , Exceptions must be able to be thrown out to catch ,python Use in raise Throw the specified exception

Use raise An exception , Bring out the exception , Call... With an instance raise sentence , Trigger exception

>>> raise Exception

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

Exception

>>> raise NameError("This is NameError")

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

NameError: This is NameError

adopt These two examples , It can be seen that , The first instance throws a normal exception without relevant error information

The second outputs some error messages ;

If you just want to know if an exception has been thrown , I don't want to deal with it , Use one raise You can throw an exception

try:raise NameError(" This is a NameError")except NameError:print(" Catch NameError") #  No addition  raise, Output the corresponding character to end => Catch NameError
try:raise NameError(" This is a NameError")except NameError:print(" Catch NameError")raise=> Catch NameError
Traceback (most recent call last):
 File "d:/VSCode/Untitled-1.py", line 4, in <module> raise NameError(" This is a NameError")
NameError:  This is a NameError

In this way NameError The exception is thrown out ,raise You can throw deeper and more detailed exception information

 

Python Important built-in exception classes

Exception: Regular error base class

AttributeError: Object does not have this property

IOError: Input / Output operation failed

IndexError: There is no index in the sequence

KeyError: There is no key in the map

NameError: Not a statement / Initialize object ( There is no attribute )

SyntaxError:python Grammar mistakes

SystemError: General interpreter system error

ValueError: Invalid parameter passed in