Python exception learning notes and Python learning notes

Source: Internet
Author: User

Python exception learning notes and Python learning notes

Exceptions are a very important type in Python. They are different from syntax errors and are errors caused during program running. Python has many built-in exceptions, such as IOError, NameError, KeyboardInterrupt. For more exceptions, click here.

The significance of an exception is to provide a more elegant running method. For example, you can write a calculator in Python. If you enter an object that cannot be computed, you can throw an exception and handle it as follows:

while True:  try:    x= int(input('Please In enter A number:'))    print "Your Input is %s"%x    break  except Exception,e:    print e

Python is an object-oriented language. Exceptions are also objects. You can use dir (Exception) to view the attributes of the Exception class, as shown in the following code: ['_ class __', '_ delattr _', '_ dict _', '_ doc _', '_ format _', '_ getattribute __', '_ getitem _', '_ getslice _', '_ hash _', '_ init _', '_ new __', '_ reduce _', '_ performance_ex _', '_ repr _', '_ setattr _', '_ setstate __', '_ sizeof _', '_ str _', '_ subclasshook _', '_ unicode _', 'args ', 'message'], except for the args and message, the rest are their internal attributes, where args is A parameter of the type passed to the constructor of the exception class is a primitive parameter. Some built-in functions, such as IOError, require it to receive multiple parameters. Others directly pass an error message string.

Python exceptions can be checked using the try statement. Any code in the try statement block will be monitored to check whether exceptions are generated. The retry t checks the type of exceptions based on input, and execute the code in memory T. So here, I can't help wondering, what are the two parameters after limit t? What if the first parameter is of the error type? It is detected that it is an Exception instance, that is, it is a specific Exception object generated by the Exception class.
What if a custom exception occurs? Python stipulates that all exceptions must be inherited from the Exception class directly or indirectly, as follows:

#!/usr/bin/env pythonclass MyError(Exception):  def __init__(self,*args):    self.value=args[0]  def __str__(self):    return repr(self.value)def showname(*args):  if args:    print args  else:    raise MyError('Error: need 1 arguments at last, 0 Input')

Save this file as showname. py. Other modules can call the showname function and check the execution result:

#!/usr/bin/env pythonimport shownametry:  showname.showname()except showname.MyError,e:  print e

It is worth noting that: 1. raise is used to throw exceptions in python; 2. Because all exceptions inherit from exceptions, when you are not sure about the Exception type, exception can be taken directly after the occurrence t to capture all exceptions. 3. All attributes in the Exception can be redefined due to the inheritance of exceptions, you can also add attributes to custom exceptions.

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.