(Python) exception handling try...except, raise First, try...except Sometimes when we write a program, there are some errors or exceptions that cause the program to terminate. For example, when division is done, the divisor is 0, which causes a zerodivisionerror Example: ?
1234 |
a = 10 b = 0 c = a / b print "done" |
Operation Result: Traceback (most recent): File "c:/users/lirong/pycharmprojects/untitled/openfile.py", line 3, <module> C=a/b Zerodivisionerror:integer division or modulo by zero We found that the program was interrupted because of Zerodivisionerror, and the statement print "done" was not running. To handle the exception, we use Try...except to change the code: ?
12345678 |
a
=
10
b
=
0
try
:
c
=
a
/
b
print c
except ZeroDivisionError,e:
print e.message
print "done"
|
Operation Result: Integer division or modulo by zero Done This way, the program does not break because of an exception, and the print "done" statement executes normally. We put statements that could have errors in the Try module and use except to handle exceptions. Except can handle a specialized exception, or it can handle an exception in a set of parentheses, and if no exception is specified after except, all exceptions are handled by default. Every try must have at least one except Handling a set of exceptions can be written like this (where E represents an instance of the exception): ?
1234 |
try : pass except (IOError ,ZeroDivisionError),e: print e |
Try .... except...else statement, when no exception occurs, the statement in else is executed. Example: ?
12345678910 |
a
=
10
b
=
0
try
:
c
= b
/ a
print c
except (IOError ,ZeroDivisionError),x:
print x
else
:
print "no error"
print "done"
|
Operation Result: 0 No error Done Second, raise throws an exception Example: If the input data is not an integer, a valueerror is raised ?
12345 |
inputValue = input ( "please input a int data :" ) if type (inputValue)! = type ( 1 ): raise ValueError else : print inputValue |
Suppose you enter 1.2 and run the result as: Please input a int data:1.2 Traceback (most recent): File "c:/users/lirong/pycharmprojects/untitled/openfile.py", line 3, <module> Raise ValueError ValueError If you enter 1, the result of the operation is: Please input a int data:1 1 Third, try ... finally The statements in finally are executed, regardless of whether the exception occurred or not, until the end of the program. ?
123456 |
a = 10 b = 0 try : print a / b finally : print "always excute" |
Operation Result: Traceback (most recent): Always Excute File "c:/users/lirong/pycharmprojects/untitled/openfile.py", line 4, <module> Print A/b Zerodivisionerror:integer division or modulo by zero Although an exception occurs, the statements in finally can be executed normally before the program terminates. The finally statement can also be used with the except statement. ?
12345678 |
a = 10 b = 0 try : print a / b except : print "error" finally : print "always excute" |
Operation Result: Error Always Excute Iv. Customizing an Exception class Customize a MyException class, inheriting exception. ?
1234 |
class MyException(Exception): def __init__( self ,message): Exception.__init__( self ) self .message = message |
If the number entered is less than 10, a MyException exception is thrown: ?
123456 |
a
=
input
(
"please input a num:"
)
if a<
10
:
try
:
raise MyException(
"my excepition is raised "
)
except MyException,e:
print e.message
|
Operation Result: Please input a num:1 My excepition is raised Five, Python all the standard exception class:
Exception name |
Description |
Baseexception |
base class for all exceptions |
Systemexit |
Interpreter Request exited |
Keyboardinterrupt |
User interrupt execution (usually input ^c) |
Exception |
base class for general errors |
Stopiteration |
There are no more values for iterators |
Generatorexit |
Generator (generator) exception occurred to notify exit |
Systemexit |
Python Interpreter Request Exit |
StandardError |
Base class for all built-in standard exceptions |
Arithmeticerror |
base class for all numeric calculation errors |
Floatingpointerror |
Floating-point calculation error |
Overflowerror |
Numeric operation exceeds maximum limit |
Zerodivisionerror |
Except (or modulo) 0 (all data types) |
Assertionerror |
Assertion statement failed |
Attributeerror |
Object does not have this property |
Eoferror |
No built-in input, EOF Mark reached |
EnvironmentError |
Base class for operating system errors |
IOError |
Input/output operation failed |
OSError |
Operating system error |
Windowserror |
System call failed |
Importerror |
Failed to import module/object |
Keyboardinterrupt |
User interrupt execution (usually input ^c) |
Lookuperror |
base class for invalid data queries |
Indexerror |
There is no such index (index) in the sequence |
Keyerror |
This key is not in the map |
Memoryerror |
Memory overflow error (not fatal for Python interpreter) |
Nameerror |
Object not declared/initialized (no attributes) |
Unboundlocalerror |
To access uninitialized local variables |
Referenceerror |
Weak references (Weak reference) attempt to access objects that have been garbage collected |
RuntimeError |
General run-time errors |
Notimplementederror |
Methods that have not been implemented |
SyntaxError |
Python syntax error |
Indentationerror |
Indentation Error |
Taberror |
Tab and Space Mix |
Systemerror |
General Interpreter system error |
TypeError |
An operation that is not valid for type |
ValueError |
Invalid parameter passed in |
Unicodeerror |
Unicode-related errors |
Unicodedecodeerror |
Error in Unicode decoding |
Unicodeencodeerror |
Unicode encoding Error |
Unicodetranslateerror |
Unicode Conversion Error |
Warning |
Base class for warnings |
Deprecationwarning |
Warnings about deprecated features |
Futurewarning |
Warning about the change in the construction of future semantics |
Overflowwarning |
Old warning about auto-promotion to Long integer |
Pendingdeprecationwarning |
Warnings about attributes that will be discarded |
Runtimewarning |
Warning for suspicious run-time behavior (runtime behavior) |
Syntaxwarning |
Warning of suspicious syntax |
Userwarning |
Warnings generated by user code |
|