Python Learning Notes (exceptions)

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

What is an 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/0

Traceback (most recent):
File "<pyshell#0>", line 1, in <module>
1/0
Zerodivisionerror:integer division or modulo by zero
>>>

Make an error in your own way raise statement

>>> 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
>>>

View built-in exceptions in the exceptions module

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

>>> Raise Arithmeticerror

Traceback (most recent):
File "<pyshell#6>", line 1, in <module>
Raise Arithmeticerror
Arithmeticerror
>>>

Custom exception Classes

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 Somecustomexception (Exception):
Pass

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 (' Please enter the first number: ')
Y=input (' Please enter the second number: ')
Print x/y

Please enter the first number:10
Please enter the second number:0

Traceback (most recent):
File "f:/python/mydemo/except.py", line 3, <module>
Print x/y
Zerodivisionerror:integer division or modulo by zero
>>>

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

Try
X=input (' Please enter the first number: ')
Y=input (' Please enter the second number: ')
Print x/y
Except Zerodivisionerror:
print ' The second number can\ ' t be zero '

------------

Please enter the first number:10
Please enter the second number:0
The second number can ' t be zero
>>>

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 Muffledcalculator:
Muffled=false
Def calc (self,expr):
Try
return eval (expr)
Except Zerodivisionerror:
If self.muffled:
print ' Division by zero ' illegal '
Else
Raise

------------

>>> Calculator=muffledcalculator ()
>>> calculator.calc (' 10/2 ')
5
>>> calculator.calc (' 10/0 ')

Traceback (most recent):
File "<pyshell#2>", line 1, in <module>
Calculator.calc (' 10/0 ') #没有屏蔽
File "f:/python/mydemo/except.py", 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 one except clause

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

Enter the first number:10
Enter the second number: ' Hello,world '

Traceback (most recent):
File "f:/python/mydemo/except.py", line 4, <module>
Print x/y
typeerror:unsupported operand type (s) for/: ' int ' and ' str '
>>>

Because the EXCEPT clause only checks for Zerodivisionerror exceptions, this exception misses the check, and in order to catch the exception, we can add a except clause to the TRY/EXCEPT statement

Try
X=input (' Enter the first number: ')
Y=input (' Enter the second number: ')
Print x/y
Except Zerodivisionerror:
print ' The second number can\ ' t be zero '
Except TypeError:
print ' That wasn\ ' t a number,was it? '

--------------------------

>>>
Enter the first number:10
Enter the second number: ' hello,world! '
That wasn ' t a number,was it?
>>>

Catch two exceptions with one block

Try
X=input (' Enter the first number: ')
Y=input (' Enter the second number: ')
Print x/y

Snapping objects

Try
X=input (' Enter the first number: ')
Y=input (' Enter the second number: ')
Print x/y
Except (Zerodivisionerror,typeerror,nameerror), E:
Print E

-----------------

>>>
Enter the first number:10
Enter the second Number:2
5
>>>
>>> ================================ RESTART ================================
>>>
Enter the first number:10
Enter the second number:0
Integer division or modulo by zero
>>> ================================ RESTART ================================
>>>
Enter the first number:10
Enter the second number: ' Hello,world '
Unsupported operand type (s) for/: ' int ' and ' str '
>>>

Real Catch-all

Even if the program can handle several kinds of exceptions, some exceptions will not be processed, such as the last division example, enter a space:

Enter the first number:

Traceback (most recent):
File "f:/python/mydemo/except.py", line 2, <module>
X=input (' Enter the first number: ')
File "<string>", line 0

^
syntaxerror:unexpected EOF while parsing
>>>

So we can ignore all exception classes in the EXCEPT clause

Try
X=input (' Enter the first number: ')
Y=input (' Enter the second number: ')
Print x/y
Except
print ' Something wrong happend ... '

--------------

>>>
Enter the first number:10
Enter the second number:0
Something wrong happend ...
>>> ================================ RESTART ================================
>>>
Enter the first number:
Something wrong happend ...
>>>

Everything

While True:

Try
X=input (' Enter The first number: ')
Y=input (' Enter The second number: ')
value=x/y
print ' x/y is ', value
Except
print ' Invalid input. Please try again. '
Else
Break

--------------------

Enter the first number:10
Enter the second number:0
Invalid input. Please try again.
Enter the first number:10
Enter the second number: ' Hello '
Invalid input. Please try again.
Enter the first number:10
Enter the second Number:2
X/Y is 5
>>>

At last

The last finally clause is used to clean up a possible exception, and it is used in conjunction with a try clause

X=none
Try
x=1/0
Finally
print ' Cleaning up ... '
del X

-------------

Cleaning up ...

Traceback (most recent):
File "f:/python/mydemo/except.py", line 3, <module>
x=1/0
Zerodivisionerror:integer division or modulo by zero
>>>

Try
1/0
Except Nameerror:
print ' Unknown variable '
Else
print ' that went well! '
Finally
print ' cleaning up. '

Exceptions and functions

If the exception is not handled within the function, it propagates to the function call until the program terminates with a stack trace

def faulty ():
Raise Exception (' someting is wrong ')
Def ignore_exception ():
Faulty ()
Def handle_exception ():
Try
Faulty ()
Except
print ' Exception handled '

----------------------------

>>> ignore_exception ()

Traceback (most recent):
File "<pyshell#1>", line 1, in <module>
Ignore_exception ()
File "f:/python/mydemo/except.py", line 4, in Ignore_exception
Faulty ()
File "f:/python/mydemo/except.py", line 2, in faulty
Raise Exception (' someting is wrong ')
Exception:someting is wrong
>>> handle_exception ()
Exception handled
>>>

Python Learning Notes (Exception)

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.