Exception Handling,

Source: Internet
Author: User

Exception Handling,
I. Preface

In the programming process, in order to increase friendliness, when a program encounters a bug, the error information is generally not displayed to the user, but a prompt page. In other words, the user is not allowed to see the yellow pages !!!

Ii. Usage 2.1 Basic Format
try:    passexcept Exception as e:    pass
2.2 capture an exception

Before the code is run, we predict that some errors/exceptions will occur, so that we can capture them without program running crash.

Names = ['Tom ', 'Jerry'] try: names [3] cannot t IndexError as e: print ('index error: ', e) # output Index error: list index out of range
More than 2.3 exception errors

If our code is running, there will be multiple exception errors, you can write them all.

Names = ['Tom ', 'Jerry'] data = {'name': 'bigberg '} try: print (names [1]) print (data ['age']) failed t IndexError as e: print ('index error: ', e) failed t KeyError as e: print ("no Key:", e) # The output Jerry does not have this Key: 'age'

This capture exception is from top to bottom. If there is an error above, the capture exception will be triggered and the following error will not be captured.

2.4 write multiple exceptions together

Sometimes it may be difficult to write a counter t for every exception. You can write it together.

Names = ['Tom ', 'Jerry'] data = {'name': 'bigberg '} try: print (names [2]) print (data ['age']) failed T (IndexError, KeyError) as e: print ('exception error: ', e) # output Exception error: list index out of range

This is easy to write, but it cannot clearly show the specific error.

2.5 catch all exceptions in a unified manner (Exception)

Most exception errors can be captured.

Names = ['Tom ', 'Jerry'] data = {'name': 'bigberg '} try: print (names [1]) print (data ['name']) for I in range (len (name): passexcept IndexError as e: print ('index error: ', e) failed t KeyError as e: print ("No such Key :", e) failed t Exception as e: print ("error:", e) # output Jerrybigberg error: name 'name' is not defined
2.6 else: No exception is caught, everything is normal
Names = ['Tom ', 'Jerry'] data = {'name': 'bigberg '} try: print (names [1]) print (data ['name']) for I in range (len (names): passexcept IndexError as e: print ('index error: ', e) failed t KeyError as e: print ("No such Key :", e) failed t Exception as e: print ("error:", e) else: print ('Everything OK ') # output Jerrybigberg everything OK
2.7 finally: whether there are any exceptions, run
Names = ['Tom ', 'Jerry'] data = {'name': 'bigberg '} try: print (names [1]) print (data ['age']) for I in range (len (names): passexcept IndexError as e: print ('index error: ', e) failed t KeyError as e: print ("No such Key :", e) failed t Exception as e: print ("error:", e) else: print ('Everything okay ') finally: print ("---------------") print (' whether there are any errors, run ') print (' I have been executed in finally ') # output Jerry does not have this Key: 'age' --------------- whether there is any error, run it in finally, executed
Iii. Custom exceptions
Class MyException (Exception): def _ init _ (self, msg): self. message = msg def _ str _ (self): return self. messagetry: raise MyException ("You have no chance with me, please come back! ") # Write error message failed t MyException as e: print (e)
Iv. Exception types
1 AttributeError attempts to access a tree without an object, such as foo. x, but foo has no attribute x 2 IOError input/output exception. Basically, file 3 ImportError cannot be opened and modules or packages cannot be introduced; basically it is a path problem or name error 4 IndentationError syntax error (subclass); the Code is not correctly aligned with the 5 IndexError subscript index beyond the sequence boundary. For example, when x has only three elements, however, I tried to access x [5] 6 KeyError. I tried to access the key that does not exist in the dictionary. 7 KeyboardInterrupt Ctrl + C was pressed 8 NameError. The Python code of variable 9 SyntaxError, which is not assigned to the object, is invalid, code cannot be compiled (I personally think this is a syntax error and I wrote it wrong) 10 TypeError passed in object type and the requirement does not meet 11 UnboundLocalError attempts to access a local variable that has not been set yet, basically, because there is another global variable with the same name, 12 leads you to think that you are accessing it 13 ValueError and passing in a value that is not expected by the caller, even if the value type is correct 14 15 common exceptions
View Code
More exceptions
View Code

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.