Python exception handling mechanism

Source: Internet
Author: User

There are also various exception handling mechanisms in the Python programming language. In fact, its application method is similar to that of C. Here, we will analyze the application of Python exceptions in detail and hope to help you.

 
 
  1. >>>>>>   
  2. try:   
  3. raise Exception("a", "b")   
  4. except Exception,e: print e finally:   
  5. print "final" ('a', 'b')('a', 'b') final   
  6. >>>>>>  

You can also process multiple Python exception filters.

 
 
  1. >>>>>>   
  2. try: raise EOFError("aa", "bb")   
  3. except RuntimeError, e: print "[RuntimeErro]: ", e except EOFError, e:   
  4. print "[EOFError]: ", e except Exception, e: print "[Error]: ", e finally:   
  5. print "final" [EOFError]: ('aa', 'bb') final   
  6. >>>>>> 

In addition to exception parameters, we can also use sys methods to obtain exception information.

 
 
  1. >>>>>> import sys >>>>>>   
  2. try: raise RuntimeError("the runtime error raised") 
  3. except: print sys.exc_info()   
  4. (<type 'exceptions.RuntimeError'>, 
  5. RuntimeError('the runtime error raised',),   
  6. <traceback object at 0x00DC5CB0>)   
  7. >>>>>>  

By default, all Python Exception classes inherit from Exception.

 
 
  1. >>>>>>   
  2. class MyException(Exception): pass   
  3. >>>>>>   
  4. try: raise MyException("My Exception raised!")   
  5. except: print sys.exc_info() (<class '__main__.MyException'>,
  6.  MyException('My Exception raised!',),   
  7. <traceback object at 0x00DC58F0>)   
  8. >>>>>>  

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.