Python Exception Big Summary

Source: Internet
Author: User
Tags integer division
Python uses exception objects (exception object) to represent exception conditions. An exception is thrown when an error is encountered. If the exception object is not handled or captured, the program terminates execution with the so-called backtracking (Traceback, an error message):

>>> 1/0

Traceback (most recent):

File " ", line 1, in

1/0

Zerodivisionerror:integer division or modulo by zero

Raise statements

To throw an exception, you can call the raise statement using either a class (a subclass of exception) or an instance parameter number. The following example uses the built-in exception exception class:

>>> Raise Exception    #引发一个没有任何错误信息的普通异常Traceback (most recent): File "
 
  
   
  ", line 1, in< c4/>
   
    
   raise exceptionexception>>> Raise Exception (' hyperdrive overload ')   # added some exception error messages Traceback (most recent): File "
   
    
     
    ", line 1, in 
    
     
      
     raise Exception (' hyperdrive overload ') Exception:hyperdrive
    
      overload
   
    
  
   
 
  

The system comes with the built-in exception class:

>>> Import Exceptions

>>> Dir (Exceptions)

[' Arithmeticerror ', ' assertionerror ', ' attributeerror ', ' baseexception ', ' buffererror ', ' byteswarning ', ' Deprecationwarning ', ' eoferror ', ' environmenterror ', ' Exception ', ' floatingpointerror ', ' futurewarning ', ' Generatorexit ', ' IOError ', ' importerror ', ' importwarning ', ' indentationerror ', ' indexerror ', ' keyerror ', ' Keyboardinterrupt ', ' lookuperror ', ' memoryerror ', ' nameerror ', ' notimplementederror ', ' oserror ', ' overflowerror ', ' Pendingdeprecationwarning ', ' referenceerror ', ' runtimeerror ', ' runtimewarning ', ' standarderror ', ' StopIteration ', ' SyntaxError ', ' syntaxwarning ', ' systemerror ', ' systemexit ', ' taberror ', ' TypeError ', ' unboundlocalerror ', ' Unicodedecodeerror ', ' unicodeencodeerror ', ' unicodeerror ', ' unicodetranslateerror ', ' unicodewarning ', ' UserWarning ' , ' ValueError ', ' Warning ', ' windowserror ', ' zerodivisionerror ', ' __doc__ ', ' __name__ ', ' __package__ ']

Wow! Many, commonly used built-in exception classes:

Custom exceptions

Although the built-in exception classes already cover most of the situation and are sufficient for many requirements, there are times when you need to create your own exception classes.

As with other classes----just make sure you inherit from the exception class, either directly or indirectly. Like this:

>>> class Somecustomexcetion (Exception):p

Of course, you can also add some methods to this class.

Catching exceptions

We can use Try/except to implement exception capture processing.

Suppose you create a program that lets the user enter two numbers and then divide them:

x = input (' Enter the first number: ') y = input (' Enter the second number: ') print x/y# run and enter the first Number:10enter The second number:0traceback (most recent): File ' I:/python27/yichang ', line 3, in 
 
  
   
  print X/yzerodi Visionerror:integer division or modulo by zero in order to catch the exception and make some error handling, you can write: try:x = input (' Enter the first number: ') y = input (' E Nter the second number: ') print x/yexcept zerodivisionerror:print "The numbers entered cannot be 0! "#再来运行 >>>enter the first number:10enter the second number:0
 
  

The number entered cannot be 0! #怎么样? It's been a lot friendlier this time.

If we are debugging, it would be better to throw an exception, if we do not want the user to see the exception information in the process of interacting with the user. How do I turn on/off the "masking" mechanism?

Class muffledcalulator:muffled = False   #这里默认关闭屏蔽def calc (self,expr): Try:return eval (expr) except Zerodivisionerror:if Self.muffled:print ' Divsion by the Zero is Illagal ' else:raise# Run program:>>> calculator = Muffledcalulator () >>> calculator.calc (' 10/2 ') 5>>> Calculator.clac (' 10/0 ') Traceback (most recent Call last): File "
 
  
   
  ", line 1, in 
  
   
    
   calculator.clac (' 10/0 ') attributeerror:muffledcalulator Instance has no attribute ' Clac '   #异常信息被输出了 >>> calculator.muffled = True   #现在打开屏蔽 >>> Calculator.calc (' 10/0 ') Divsion by zero is illagal
  
   
 
  


multiple except clauses

If you run the above (enter two number, divide) program and enter the contents of the polygon, another exception will be generated:

try:x = input (' Enter the first number: ') y = input (' Enter the second number: ') print x/yexcept zerodivisionerror:print " The number entered cannot be 0!  "#运行输入: >>>enter the first number:10enter the second number: ' Hello.word '  #输入非数字Traceback (most recent call Last): File "I:\Python27\yichang", line 4, in 
 
  
   
  print x/ytypeerror:unsupported operand type (s) for/: ' Int. ' an d ' str '  #又报出了别的异常信息
 
  

All right! We can deal with this situation with an extra exception:

try:x = input (' Enter the first number: ') y = input (' Enter the second number: ') print x/yexcept zerodivisionerror:print "input The number cannot be 0! "Except TypeError:           # exception handling for characters print" Please enter a number! "#再来运行: >>>enter the first number:10enter the second number: ' Hello,word '

Please enter a number!

One block captures multiple exceptions

We can of course also use a block to catch multiple exceptions:

try:x = input (' Enter the first number: ') y = input (' Enter the second number: ') Print x/yexcept (Zerodivisionerror,typeerro R,nameerror):p rint "Your numbers are wrong!

"

Catch all exceptions

Even if the program handles several kinds of anomalies, such as the above program, after running, if I enter the following content

>>>enter the first number:10enter the second number:   #不输入任何内容, enter Traceback (most recent call last): File "i:\p  Ython27\yichang ", line 3, in 
 
  
   
  y = input (' Enter the second number: ') File"
  
   
    
   ", line 0^syntaxerror: Unexpected EOF while parsing
  
   
 
  

Dizzy Death! What do we do? There is always the case that we accidentally ignore the processing, if you really want to catch all the exceptions with a piece of code, you can omit all exception classes in the EXCEPT clause:

try:x = input (' Enter the first number: ') y = input (' Enter the second number: ') print X/yexcept:print ' ERROR has occurred! ' #再来输入一些内容看看 >>>enter The first number: ' Hello ' *) 0

Something went wrong!

End

Don't worry! Again, the last situation, OK, the user accidentally entered the wrong information, can you give another chance to enter? We can add a loop to protect you when you lose the right to the end:

While true:try:x = input (' Enter the first number: ') y = input (' Enter the second number: ') value = X/yprint ' x/y is ', valuee Xcept:print ' column effect input, one more time! ' #运行 >>>enter The first number:10enter the second number: column effect input, one more time! Enter the first number:10enter the second number: ' Hello ' for column effect input, one more time! Enter the first number:10enter the second number:2x/y is 5
  • 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.