#!/usr/bin/env python#-*-coding:utf-8-*-Try: Open ("Xxx.txt") #print (num) Print('test1 ....') #print (num)exceptNameerror:Print('there is an exception that is being processed ...')exceptFilenotfounderror:Print('No such file or directory')Print('test2 ....') Results: No such fileordirectorytest2 ....
You can also merge writes:
#!/usr/bin/env python#-*-coding:utf-8-*-Try: Open ("Xxx.txt") #print (num) Print('test1 ....') #print (num)except(Nameerror,filenotfounderror):##这是python3的写法 Print('there is an exception that is being processed ...')
#exceptNameerror,filenotfounderror:## #这是python2的写法Print('test2 ....') Result: There is an exception that is being processed ... test2 ....
Exception all the notation:
#!/usr/bin/env python#-*-coding:utf-8-*-Try: 11/0#Open ("Xxx.txt") #print (num) Print('test1 ....')except(nameerror,filenotfounderror):Print('If you catch an exception after you do the processing ...')exceptException:##这是python3 The method of capturing all exceptions, Python2 writes except directly: Print('If exception is used, it means that the above except does not catch an exception, and this except is bound to capture')#except Exception as RET:#print (' If exception is used, it means that the above except does not catch an exception, this except will catch ')#print (ret)Else: Print('features that do not have an exception')finally: Print('whether there is an exception, the last function to perform')Print('test2 ....')
Results:
If exception is used, it means that the above except does not catch an exception, and this except is bound to capture
Whether there is an exception, the last function to perform
Test2 ....
Python Exception handling