Exception what is exception
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 division or modulo by zero
Each exception is an instance of some classes. These instances can be thrown and captured in many ways, so that the program can catch and handle errors, rather than making the entire program fail.
Errors in your own way
Exceptions can be automatically triggered when something goes wrong.
Raise statement
To cause an Exception, you can use a class (which should be a subclass of Exception) or an instance parameter to call the raise statement. When a class is used, the program automatically creates an instance.
>>> Raise Exception
Traceback (most recent call last ):
File" ", Line 1, in
Raise Exception
Exception
>>> Raise Exception ('hyperdrive overload ')
Traceback (most recent call last ):
File" ", Line 1, in
Raise Exception ('hyperdrive overload ')
Exception: hyperdrive overload
The first example raises a common exception without any relevant error information;
In the second example, some hyperdive overload error messages are added.
There are many 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 _']
All these exceptions can be used in raise statements:
>>> Raise ZeroDivisionError
Traceback (most recent call last ):
File" ", Line 1, in
Raise ZeroDivisionError
ZeroDivisionError
>>> Raise BaseException
Traceback (most recent call last ):
File" ", Line 1, in
Raise BaseException
BaseException
Some of the most important built-in exception classes:
Class Name |
Description |
Exception |
All abnormal base classes |
AttributeError |
Property Reference or value assignment failure |
IOError |
When you try to open a non-existing file (including in other cases ), |
IndexError |
This parameter is triggered when an index that does not exist in the sequence is used. |
KeyError |
This parameter is triggered when a key that does not exist in the ing is used. |
NameError |
If the name (variable) is not found |
SyntaxError |
Triggered when the code is in the wrong format |
TypeError |
When an internal creation operation or function is applied to an object of the error type |
ValueError |
The internal creation operation or function is applied to objects of the correct type. |
ZeroDivisionError |
This parameter is triggered when the second parameter of the division or division operation is 0. |
Custom exception class
Sometimes you need to create your own exception classes.
Class SomeCustomException (Exception): pass
You can add a method to the automatic exception class. Nothing is done here.
Capture exceptions
The most interesting thing about exceptions is that they can be processed (usually called trapping or capturing exceptions ).
This function can be implemented using try/try t.
X = input ('1st number :')
Y = input ('2nd number :')
Print x/y
If the user inputs 0 as the second number, a ZeroDivisionError error occurs.
To catch exceptions and handle some errors:
Try:
X = input ('1st number :')
Y = input ('2nd number :')
Print x/y
Except t ZeroDivisionError:
Print "The 2nd number can't be zero !"
No Parameters
>>> Class MuffledCalculator:
Muffled = False
Def calc (self, expr ):
Try:
Return eval (expr)
Except t ZeroDivisionError:
If self. muffled:
Print "Division by zero is illegal"
Else:
Raise
>>> Calculator = MuffledCalculator ()
>>> Calculator. calc ('20140901 ')
5
>>> Calculator. calc ('20140901 ')
Traceback (most recent call last ):
File" ", Line 1, in
Calculator. calc ('20140901 ')
File" ", Line 5, in calc
Return eval (expr)
File" ", Line 1, in
ZeroDivisionError: integer division or modulo by zero
>>> Calculator. muffled = True
>>> Calculator. calc ('20140901 ')
Division by zero is illegal
More than one limit t clause
Try:
X = input ('1st number :')
Y = input ('2nd number :')
Print x/y
Except t ZeroDivisionError:
Print "The 2nd number can't be zero !"
If you enter "HelloWorld" as the second parameter, an error is thrown:
TypeError: unsupported operand type (s) for/: 'int' and 'str'
Because the except T clause only looks for ZeroDivisionError exceptions, this error slipped through the check and causes program termination. To catch this exception, you can add another limit t clause after the same try/try t statement:
Try:
X = input ('1st number :')
Y = input ('2nd number :')
Print x/y
Except t ZeroDivisionError:
Print "The 2nd number can't be zero !"
Handle t TypeError:
Print "That wasn't a number, was it ?"
Capture two exceptions with one block
If you need to capture multiple types of exceptions with one block, you can list them as tuples:
Try:
X = input ('1st number :')
Y = input ('2nd number :')
Print x/y
Except T (ZeroDivisionError, TypeError ):
Print "Your numers are bogus !"
Object capturing
Object capturing is useful if you want to keep the program running but want to record Errors for some reason.
Try:
X = input ('1st number :')
Y = input ('2nd number :')
Print x/y
Except T (ZeroDivisionError, TypeError), e:
Print e
Real full capture
Even if the program can handle several types of exceptions, some exceptions will still slip away from the bottom of your eyes.
Take division as an example. Press enter directly at the prompt without entering anything. An error message similar to the following will be generated:
SyntaxError: unexpected EOF while parsing
This exception escaped the try/retry t statement check. In this case, it is better to use the try/try t statement that does not capture these exceptions to hide the exceptions.
However, if you really want to capture all exceptions with a piece of code, you can ignore all Exception classes in the limit t clause:
Try:
X = input ('1st number :')
Y = input ('2nd number :')
Print x/y
Except t:
Print 'something wrong happened ...'
Warning capturing all exceptions like this is dangerous because it hides all the errors that programmers did not expect and are not ready to handle. It will also capture the user's attempt to terminate the execution of Ctrl + c, and the attempt to terminate the program using the sys. exit function, and so on. At this time, it would be better to use the Exception t Exception, e, or perform some checks on the Exception Object e.
Everything is fine
In some cases, it is useful to execute a piece of code when some bad things occur. You can add an else clause to the try/try t statement:
>>> Try:
Print 'a simple task'
Except t:
Print 'What? '
Else:
Print 'nothing'
A simple task
Nothing
Last ......
The finally clause is used to clean up possible exceptions.
>>> Try:
Print 'a simple task'
Except t:
Print 'What? '
Else:
Print 'nothing'
Finally:
Print 'clean up'
A simple task
Nothing
Clean up
Exceptions and functions
Exceptions and functions naturally work together. If an exception is thrown in a function and is not processed, it will be transmitted to the function call area. If no exception is handled there, it will continue to spread until it reaches the main program (global scope ). If no exception handler exists, the program terminates with a stack trace.
>>> Def faulty ():
Raise Exception ('Something is wrong ')
>>> Def ignore_exception ():
Faulty ()
>>> Def handle_exception ():
Try:
Faulty ()
Except t:
Print 'exception handled'
>>> Ignore_exception ()
Traceback (most recent call last ):
File" ", Line 1, in
Ignore_exception ()
File" ", Line 2, in ignore_exception
Faulty ()
File" ", Line 2, in faulty
Raise Exception ('Something is wrong ')
Exception: something is wrong
>>> Handle_exception ()
Exception handled