This article introduces Python errors and exceptions concepts Python errors and exceptions (total)
1. how to handle errors and exceptions
- Common errors
-
A: NameError
-
If True: SyntaxError
-
F = oepn('1.txt '): IOError
-
10/0: ZeropisionError
-
A = int ('D'): ValueError
-
Program running interrupted: KeyboardInterrupt
2. Python-use try_cmdt to handle exceptions (1)
try: try_suiteexcept Exception [e]: exception_block
-
Try is used to capture errors in try_suite and deliver the errors to the retry T for processing.
-
T is used to handle exceptions. if The exception is the same as the caught exception, use exception_block to handle the exception.
# case 1try: undefexcept: print 'catch an except'
# case 2try: if undefexcept: print 'catch an except'
--
# case 3try: undefexcept NameError,e: print 'catch an except',e
# case 4try: undefexcept IOError,e: print 'catch an except',e
Example
import randomnum = random.randint(0, 100)while True: try: guess = int(raw_input("Enter 1~100")) except ValueError, e: print "Enter 1~100" continue if guess > num: print "guess Bigger:", guess elif guess < num: print "guess Smaller:", guess elif guess == num: print "Guess OK,Game Over" break print '\n'3. Python uses try_cmdt to handle exceptions (2)
try: try_suiteexcept Exception1[e]: exception_block1except Exception2[e]: exception_block2except ExceptionN[e]: exception_blockN
4. use Python-try_finally
try: try_suitefinally: do_finally
-
If the try statement does not capture errors, the code executes the do_finally statement.
-
If the try statement captures errors, the program first executes the do_finally statement and then submits the captured errors to the python interpreter for processing.
5. Python-try T-else-finally
try: try_suite except: do_except finally: do_finally
-
If the try statement does not capture exceptions, run finally after the try code segment is executed.
-
If try catches an exception, execute wait t to handle the error first, and then execute finally
6. Python-with_as statement
with context [as var]: with_suite
-
The with statement is used to replace the try_effect_finall statement to make the code more concise.
-
The context expression returns an object.
-
Var is used to save the context returned object. a single return value or ancestor
-
With_suite uses the var variable to operate the context returned object
The with statement is essentially context management:
-
Context Management Protocol: inclusion method__enter__()And__exit()__To implement the two methods for objects that support this protocol
-
Context manager: defines the runtime context to be established when the with statement is executed. it is responsible for the entry and exit operations in the context of the with statement block.
-
Enter the context manager: call the manager__enter__METHOD. if the as var statement is set, the var variable accepts__enter__()Method return value
-
Exit the context manager: call the manager__exit__Method
class Mycontex(object): def __init__(self, name): self.name = name def __enter__(self): print "__enter__" return self def do_self(self): print "do_self" def __exit__(self, exc_type, exc_val, exc_tb): print "__exit__" print "Error:", exc_type, " info:", exc_valif __name__ == "__main__": with Mycontex('test context') as f: print f.name f.do_self()Whith statement application scenario:
-
File operations
-
Mutually exclusive objects between process threads, such as mutex locks
-
Other objects supporting context
2. standard exceptions and automatic exceptions 1. Python-assert and raise statements
-
Rais statement
-
The reise statement is used to actively throw an exception.
-
Syntax format: raise [exception [, args]
-
Exception: exception class
-
Args: a tuple that describes the exception information.
raise TypeError, 'Test Error'
raise IOError, 'File Not Exit'
-
Assert statement
-
Asserted statement: The assert statement is used to check whether the expression is true. if the expression is false, an AssertionError occurs.
-
Syntax format: assert expression [, args]
-
Experession: expression
-
Args: description of the judgment condition
assert 0, 'test assert'
assert 4==5, 'test assert'
2. Python-standard and custom exceptions
-
Standard Exception
-
Custom exception:
-
Python allows custom exceptions to describe exceptions that are not involved in python.
-
Custom exceptions must inherit the Exception class
-
Custom exceptions can only be triggered manually
class CustomError(Exception): def __init__(self, info): Exception.__init__(self) self.message = info print id(self) def __str__(self): return 'CustionError:%s' % self.messagetry: raise CustomError('test CustomError')except CustomError, e: print 'ErrorInfo:%d,%s' % (id(e), e)
For more articles about Python errors and exceptions, refer to PHP!