Python exception study notes

  • 2020-04-02 14:33:50
  • OfStack

Exceptions are a very important type in Python and, unlike syntax errors, are errors that are thrown while the program is running. Python built-in many exceptions, such as IOError, NameError, KeyboardInterrupt etc., can more exceptions (link: http://www.tutorialspoint.com/python/standard_exceptions.htm).

The point of exceptions is to provide a more elegant way to run them, such as writing a calculator in Python that throws an exception and handles it if the user enters an object that cannot be evaluated, 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 themselves are objects, dir(Exception) to see the properties of the Exception class, As follows: [' magic __class__ ', '__delattr__', '__dict__' and '__doc__', '__format__', 'the.__getattribute__', 'the __getitem__' and '__getslice__', '__hash__' and '__init__', '__new__' and '__reduce__', '__reduce_ex__' and '__repr__', 's function,' s function,' s function,' s function,' s function,' s function,' s function,' s function,' s function,' s function,' s function,' s function,' s function,' s function,' s function,' s function. Others simply pass an error message string.

Python exceptions can be checked by a try statement, any code in a try block is monitored for exception generation, except that the type of exception is checked against the input and the code inside except is executed. So, what are the two arguments after except? If the first is the wrong type, what about the second parameter? It is detected as an instance of Exception, that is, as a concrete Exception object generated by the Exception class.
What if the user customizes an exception? Python states that all exceptions must be directly or indirectly inherited from the Exception class, as follows:


#!/usr/bin/env python
class 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 the file as showname.py, and other modules can introduce the call to the showname function and detect the result of its execution:


#!/usr/bin/env python
import showname
try:
  showname.showname()
except showname.MyError,e:
  print e

The notable points are :1. Raise is used in python to throw an exception; 2. 2. Since all exceptions are inherited from Exception, it is possible to catch all exceptions directly after except when the type of Exception is uncertain. 3. Due to the inheritance of the exception, all the attributes in the exception can be redefined or added to the custom exception.


Related articles: