Basic Python Tutorial _ Learning Note 10: Exceptions

Source: Internet
Author: User
Tags integer division stack trace terminates

Exception what is an exception

Python uses an exception object to represent an exception condition. An exception is thrown when an error is encountered. Assuming that the exception object is not handled or captured, the program terminates its operation with so-called backtracking (Traceback, an error message):

>>> 1/0

Traceback (most recent):

File "<pyshell#0>", line 1, in <module>

1/0

Zerodivisionerror:integer division or modulo by zero

Each exception is an instance of some class that can be thrown, and can be captured in very many ways, so that the program can catch the error and handle it instead of having the entire program fail.

Make mistakes in your own way

Exceptions can be initiated when something goes wrong.

RaiseStatement

To throw an exception, you can use a class (which should be a subclass of Exception) or an instance parameter to invoke the raise statement. When you use a class, the program creates instances on its own initiative.

>>> Raise Exception

Traceback (most recent):

File "<pyshell#1>", line 1, in <module>

Raise Exception

Exception

>>> Raise Exception ('hyperdrive overload')

Traceback (most recent):

File "<pyshell#2>", line 1, in <module>

Raise Exception (' hyperdrive overload ')

Exception:hyperdrive overload

The first example raises a common exception that does not have any information about the error;

The second example adds some hyperdive overload error messages.

There are very many built-in exception classes.

>>> 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__ ']

All of these exceptions can be used with raise statements:

>>> Raise Zerodivisionerror

Traceback (most recent):

File "<pyshell#6>", line 1, in <module>

Raise Zerodivisionerror

Zerodivisionerror

>>> Raise Baseexception

Traceback (most recent):

File "<pyshell#7>", line 1, in <module>

Raise Baseexception

Baseexception

Some of the most important built-in exception classes :

Class name Descriptive narrative
Exception base class for all exceptions
Attributeerror Thrown when an attribute reference or assignment fails
IOError Thrown when an attempt is made to open a file that does not exist (contains other conditions)
Indexerror Thrown when using an index that does not exist on a sequence
Keyerror Thrown when a key that does not exist in the map is used
Nameerror Thrown when a name (variable) is not found
SyntaxError Thrown when the code is in the wrong form
TypeError Thrown when a built-in operation or function is applied to an object of the wrong type
ValueError Thrown when a built-in operation or function is applied to an object of the correct type, but the object uses an inappropriate value.
Zerodivisionerror The second parameter in a division or modulo operation is 0 thrown when

Define the Exception class yourself

There are times when you need to create your own exception class.

Class Somecustomexception (Exception): Pass

You can add methods to your own active exception class, and nothing is done here.

Catching exceptions

The most interesting thing about exceptions is being able to handle them (often called trapping or catching anomalies).

This feature can be implemented using try/except .

X=input (' 1st number: ')

Y=input (' 2nd number: ')

Print x/y

Assuming the user enters 0 as the second number, a zerodivisionerror exception occurs.

To catch exceptions and make some error handling:

Try

X=input (' 1st number: ')

Y=input (' 2nd number: ')

Print x/y

Except Zerodivisionerror:

Print "The 2nd number can ' t be zero!"

Look, no number.

>>> class Muffledcalculator:

Muffled=false

Def calc (self,expr):

Try

return eval (expr)

Except Zerodivisionerror:

If self.muffled:

Print "Division by zero is illegal"

Else

Raise

>>> Calculator=muffledcalculator ()

>>> calculator.calc (' 10/2 ')

5

>>> calculator.calc (' 10/0 ')

Traceback (most recent):

File "<pyshell#22>", line 1, in <module>

Calculator.calc (' 10/0 ')

File "<pyshell#19>", line 5, Calc

return eval (expr)

File "<string>", line 1, in <module>

Zerodivisionerror:integer division or modulo by zero

>>> Calculator.muffled=true

>>> calculator.calc (' 10/0 ')

Division by zero is illegal

More than oneexceptclauses

Try

X=input (' 1st number: ')

Y=input (' 2nd number: ')

Print x/y

Except Zerodivisionerror:

Print "The 2nd number can ' t be zero!"

Assuming that the user enters "HelloWorld" as the second parameter, an error is raised:

typeerror:unsupported operand type (s) for/: ' int ' and ' str '

Because the except clause only looks for zerodivisionerror exceptions, this error slips through the check and causes the program to terminate. To catch this exception, You can add a except clause directly after the same try/except statement:

Try

X=input (' 1st number: ')

Y=input (' 2nd number: ')

Print x/y

Except Zerodivisionerror:

Print "The 2nd number can ' t be zero!"

Except TypeError:

Print "That wasn ' t a number,was it?"

Catch two exceptions with one block

Suppose you need to catch more than one type of exception with a block, and you can list them as tuples:

Try

X=input (' 1st number: ')

Y=input (' 2nd number: ')

Print x/y

except (Zerodivisionerror,typeerror) :

Print "Your numers is Bogus!"

Snapping objects

If you want the program to continue, but for some reason you want to record the error, capturing the object is very useful.

Try

X=input (' 1st number: ')

Y=input (' 2nd number: ')

Print x/y

Except (Zerodivisionerror,typeerror), E:

Print E

Real Catch-all

Even though the program can handle several types of exceptions, some exceptions will slip through the nose.

In the case of division, press ENTER directly at the prompt, and no matter what, you will get an error message similar to the following:

syntaxerror:unexpected EOF while parsing

This exception escaped the check of the try/except statement. In this case, instead of hiding the exception with try/except statements that don't catch these exceptions , you might as well let the program crash immediately.

But suppose you really want to catch all the exceptions in a piece of code, and you can ignore all of the exception classes in the except clause:

Try

X=input (' 1st number: ')

Y=input (' 2nd number: ')

Print x/y

Except

print ' Something wrong happened ... '

Warning: Catching all exceptions like this is critical because it hides all programs the ape has not thought of and is not ready to deal with the error. It will capture the user's attempt to terminate the program using the sys.exit function, and so on. It is better to use except Exception,e , or to check the exception object e .

Everything

In some cases, it is very practical to run a piece of code when something bad happens, and you can add an else clause to the try/except statement:

>>> Try:

print ' A simple task '

Except

print ' What? '

Else

print ' Nothing '

A Simple Task

Nothing

At last......

A finally clause that is used to clean up after a possible exception.

>>> Try:

print ' A simple task '

Except

print ' What? '

Else

print ' Nothing '

Finally

print ' Clean up '

A Simple Task

Nothing

Clean up

Exceptions and functions

Exceptions and functions work very naturally together. Assuming an exception is thrown within a function and not processed, it propagates to the place where the function is called. Assuming there is no handling exception, it will continue to propagate and reach the main program (global scope). Assuming there are no exception handlers, the program terminates with a stack trace.

>>> def faulty ():

Raise Exception (' Something is wrong ')

>>> def ignore_exception ():

Faulty ()

>>> def handle_exception ():

Try

Faulty ()

Except

print ' Exception handled '

>>> ignore_exception ()

Traceback (most recent):

File "<pyshell#58>", line 1, in <module>

Ignore_exception ()

File "<pyshell#51>", line 2, in Ignore_exception

Faulty ()

File "<pyshell#48>", line 2, in faulty

Raise Exception (' Something is wrong ')

Exception:something is wrong

>>> handle_exception ()

Exception handled

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.