Python uses an exception object to indicate exceptions. python uses an exception object to indicate exceptions. An error occurs. If the exception object is not processed or captured, the program terminates the execution with the so-called trace (Traceback, an error message:
>>> 1/0
Traceback (most recent call last ):
File" ", Line 1, in
1/0
ZeroDivisionError: integer pision or modulo by zero
Raise statement
To cause an Exception, you can call the raise Statement by using a class (subclass of Exception) or the number of instance parameters. The following example uses the built-in Exception class:
>>> Raise Exception # a common Exception without any error message. Traceback (most recent call last): File"
", Line 1, in
Raise ExceptionException >>> raise Exception ('hyperdrive overload') # added some Exception error information Traceback (most recent call last): File"
", Line 1, in
Raise Exception ('hyperdrive overload') Exception: hyperdrive overload
Built-in exception classes:
>>> Import exceptions
>>> Dir (exceptions)
['Arithmeticerror', 'assertionerror', 'bubuteerror', 'baseexception', 'buffererror', 'byteswarning', 'describerationwarning', 'eoferror', 'environmenterror ', 'exception', 'floatingpointerror ', 'ureurewarning', 'generatorexit', 'ioerror', 'importererror', 'importwarning', 'inputationerror', 'indexerror', 'keyerror ', 'keyboardinterrupt', 'lookuperror ', 'memoryerror', 'nameerror', 'notimplementederror', 'osserror ', 'overflowerror', 'failed', 'referenceerror', 'runtimeerror ', 'runtimewarning', 'standardererror', 'stopiteration', 'syntaxerror', 'syntaxwarning', 'systemerror', 'systemdelete', 'taberror', 'typeerror', 'unboundlocalerror ', 'unicodedecodeerror', 'unicodeencodeerror', 'unicodeerror', 'authorization', 'unicodewarning', 'userwarning', 'valueerror', 'warning', 'windowsererror', 'zerodivisionerror ', '_ doc _', '_ name _', '_ package _']
Wow! Many common built-in exception classes:
Custom exception
Although the built-in exception classes already cover most of the situations, and many requirements are sufficient, you still need to create your own exception classes sometimes.
Just like other common classes-make sure that they are inherited from the Exception class, whether directly or indirectly. As shown below:
>>> Class someCustomExcetion (Exception): pass
Of course, you can also add some methods for this class.
Capture exceptions
We can use try/try T to capture and handle exceptions.
Assume that a program is created to allow the user to input two numbers and then perform division:
X = input ('Enter the first number: ') y = input ('Enter the second number:') print x/y # run and Enter the first number: 10 Enter the second number: 0 Traceback (most recent call last): File "I:/Python27/yichang", line 3, in
Print x/yZeroDivisionError: integer pision or modulo by zero to catch exceptions and handle some errors, you can write as follows: try: x = input ('Enter the first number :') y = input ('Enter the second number: ') print x/yt t ZeroDivisionError: print "the input number cannot be 0! "# Run Again> Enter the first number: 10 Enter the second number: 0
The input number cannot be 0! # How? This time it is much more friendly.
It would be better if an exception is thrown during debugging, and if you do not want to see the exception information during interaction with the user. So how do I enable/disable the "blocking" mechanism?
Class MuffledCalulator: muffled = False # def calc (self, expr): try: return eval (expr) blocks T ZeroDivisionError: if self. muffled: print 'divsion by zero is illagal' else: raise # run the program: >>> calculator = MuffledCalulator () >>> calculator. calc ('000000') 5 >>> calculator. clac ('200') Traceback (most recent call last): File"
", Line 1, in
Calculator. clac ('200') AttributeError: MuffledCalulator instance has no attribute 'clac' # The exception information is output >>> calculator. muffled = True # enable blocking now >>> calculator. calc ('200') Divsion by zero is illagal
Multiple limit T clauses
If you run the above (enter two numbers and divide them) program and input the following content, another exception will occur:
Try: x = input ('Enter the first number: ') y = input ('Enter the second number:') print x/yt t ZeroDivisionError: print "the input number cannot be 0! "# Run input >>> Enter the first number: 10 Enter the second number: 'Hello. word' # enter a non-numeric Traceback (most recent call last): File "I: \ Python27 \ yichang", line 4, in
Print x/yTypeError: unsupported operand type (s) for/: 'int' and 'str' # Another exception message is reported.
Okay! We can add an exception to handle this situation:
Try: x = input ('Enter the first number: ') y = input ('Enter the second number:') print x/yt t ZeroDivisionError: print "the input number cannot be 0! "Handle T TypeError: # handle character exceptions print" Please enter a number! "# Run again: >>> Enter the first number: 10 Enter the second number: 'Hello, Word'
Enter a number!
One block captures multiple exceptions
Of course, we can also use one block to capture multiple exceptions:
Try: x = input ('Enter the first number: ') y = input ('Enter the second number:') print x/yexcept (ZeroDivisionError, TypeError, NameError ): print "your number is incorrect!
"
Catch all exceptions
Even if the program handles several exceptions, such as the above program, after running it, what if I input the following content?
>>> Enter the first number: 10 Enter the second number: # without entering any content, press Enter Traceback (most recent call last): File "I: \ Python27 \ yichang ", line 3, in
Y = input ('Enter the second number: ') File"
", Line 0 ^ SyntaxError: unexpected EOF while parsing
Dizzy ~! What should we do? There are always situations where we accidentally ignore the handling. if you really want to catch all exceptions with a piece of code, you can ignore all exception classes in the except t clause:
Try: x = input ('Enter the first number: ') y = input ('Enter the second number:') print x/yt t: print' an error occurred! '# Enter some content> Enter the first number: 'Hello' *) 0
An error occurred!
End
Don't worry! Let's talk about the last situation. well, the user accidentally entered the wrong information. can you give me another chance to enter it? We can add a loop to make it end only when you lose the right:
While True: try: x = input ('Enter the first number: ') y = input ('Enter the second number :') value = x/yprint 'X/y is ', value0000t: print' column effect input, and then try again! '# Run >>> Enter the first number: 10 Enter the second number: Column-effect input. come again! Enter the first number: 10 Enter the second number: 'Hello' column effect input, and then try again! Enter the first number: 10 Enter the second number: 2x/y is 5