Python Basic Learning Notes (ix)

Source: Internet
Author: User
Tags integer division

Python exception

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/0traceback (most recent):  File "<pyshell#0>", line 1, in <module>    1/ 0zerodivisionerror: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 "<pyshell#1>", Line 1, in <module>    raise exceptionexception>>> Raise Exception (' hyperdrive overload ')   # Added some exception error messages Traceback (most recent call last):  File ' <pyshell#2> ', line 1, in <module>    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 <module>    prin T X/yzerodivisionerror:integer division or modulo by zero

To catch an exception and make some error handling, you can write:

Try:    x = input (' Enter the first number: ')    y = input (' Enter the second number: ')    print x/yexcept zerodivision Error:print "The number entered cannot be 0! "#再来云行 >>> Enter the first number:10enter the second number:0 number 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 zero is Illagal '            else:                raise# Run Program: >>> calculator = muffledcalulator () >>> calculator.calc (' 10/2 ') 5>>> Calculator.clac (' 10/0 ') Traceback (most recent):  File "<pyshell#30>", line 1, in <module>    Calculator.clac (' 10 /0 ') Attributeerror:muffledcalulator instance has no attribute ' Clac '   #异常信息被输出了 >>> calculator.muffled = True   

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 zerodivision Error:print "The number entered cannot be 0! "#运行输入:>>> Enter the first number:10enter the second number: ' Hello.word '  #输入非数字Traceback (most recent CAL L last):  File "I:\Python27\yichang", line 4, in <module>    print x/ytypeerror:unsupported operand type (s) fo R/: ' int ' and ' 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 Zerodivis Ionerror:    Print "The number entered 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 the numbers!

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 (zerodivisio Nerror,typeerror,nameerror):    print "Your number is 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:\Python27\yichang", line 3, in <module>    y = input (' Enter the second number: ')  File "<string>", Li NE 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 ' Something wrong has happened! ' #再来输入一些内容看看 >>> Enter The first number: ' Hello ' *) 0 error has occurred!

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/y< C5/>print ' x/y is ', value
Break except: 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

Python Basic Learning Notes (ix)

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.