For reprinting, please indicate the source:
http://www.cnblogs.com/why168888/p/6435956.html
This article is from: [Edwin Blog Garden]
Python error and exception concepts (total)
1. How to handle errors and exceptions
1. Common mistakes
- a: NameError
- if True: SyntaxError
- f = oepn('1.txt'): IOError
- 10/0: ZeroDivisionError
- a = int('d'): ValueError
- Program interrupt: Keyboard Interrupt
2.Python - Use try_except to handle exceptions (1)
try: try_suite except Exception [e]: exception_block
- Try is used to catch errors in try_suite and hand them over to except for processing
- Exceept is used to handle exceptions. If the exception handling and setting catch exceptions are identical, exception_block is used to handle exceptions.
# case 1 try: undef except: print 'catch an except'
# case 2 try: if undef except: print 'catch an except'
- Case 1: Exceptions can be caught because they are runtime errors
- Case 2: Exceptions cannot be caught because they are grammatical errors and pre-run errors
--
# case 3 try: undef except NameError,e: print 'catch an except',e
# case 4 try: undef except IOError,e: print 'catch an except',e
- Case 3: Exceptions can be caught because settings capture NameError exceptions
- Case 4: Exceptions cannot be caught because setting IOError does not handle NameError
Example
import random num = 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_except to handle exceptions (2)
- try-except: Handling multiple exceptions
try: try_suite except Exception1[e]: exception_block1 except Exception2[e]: exception_block2 except ExceptionN[e]: exception_blockN
4. Python-try_final use
try: try_suite finally: do_finally
- If the try statement does not catch an error, the code executes the do_final statement
- If the try statement catches errors, the program first executes the do_final statement, and then passes the captured error to the python interpreter for processing.
5. Python-try-except-else-finally
try: try_suite except: do_except finally: do_finally
- If the try statement does not catch an exception, after executing the try snippet, execute finally
- If try catches an exception, first execute except to handle the error, and then execute finally
6. Python-with_as statement
with context [as var]: with_suite
- with statements are used instead of try_except_final statements to make the code more concise
- The context expression returns an object
- var is used to save context return objects, single return values or meta-ancestors
- with_suite uses var variables to manipulate context return objects
with statements are essentially context management:
- Context Management Protocol: Contains methods _enter_() and _exit ()_____, and objects supporting the protocol implement these two methods
- Context Manager: Defines the runtime context to be established when executing with statements, and is responsible for executing the entry and exit operations in the context of with statement blocks.
- Enter the context manager: Call the manager__enter_ method, and if the as var statement is set, the VaR variable accepts the return value of the _enter_() method.
- Exit Context Manager: Call 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_val if __name__ == "__main__": with Mycontex('test context') as f: print f.name f.do_self()
The while statement application scenario:
- File operation
- Mutual exclusive objects between process threads, such as mutexes
- Other objects that support context
2. Standard anomalies and automatic anomalies
1. Python-assert and raise statements
- rais statement
- The reise statement is used to actively throw exceptions
- Syntax format: raise[exception[,args]]
- Exception: exception class
- args: tuples that describe exception information
raise TypeError, 'Test Error'
raise IOError, 'File Not Exit'
- assert statement
- Assertion sentence: assert statement is used to detect whether an expression is true or false, causing Assertion Error error
- Syntax format: assert expression[,args]
- experession: expression
- args: Descriptive information for judging conditions
assert 0, 'test assert'
assert 4==5, 'test assert'
2. Python - Standard and custom exceptions
- Standard anomaly
- python built-in exceptions exist before the program executes
- Custom exceptions:
- python allows you to customize exceptions to describe exceptions not covered in python
- Custom exceptions must inherit Exception classes
- Custom exceptions can only be triggered actively
class CustomError(Exception): def __init__(self, info): Exception.__init__(self) self.message = info print id(self) def __str__(self): return 'CustionError:%s' % self.message try: raise CustomError('test CustomError') except CustomError, e: print 'ErrorInfo:%d,%s' % (id(e), e)