- Routines: using except and adding exception types
# -*- coding: UTF-8 -*- try: fh = open("a.txt",‘w‘) fh.write("This is a file for Exception test!")except IOError: print "Error, file not found or access failure!"else: print "Successful!"
Output:
[email protected]:~/code$ python test.py Successful![email protected]:~/code$ cat a.txt This is a file for Exception [email protected]
- You can also see the
write()
non-newline character by opening the A.txt
1.2. In order to test, we first a.txt to write permission to remove, and then re-execute the above code, you can find the exception caused by the inability to write
chmod -w a.txt[email protected]:~/code$ python test.py Error, file not found or access failure!
- Use exceptions without any exception type
try: 正常的操作 ......................except: 发生异常,执行这块代码 ......................else: 如果没有异常执行这块代码
- Using exceptions with multiple exception types
try: 正常的操作 ......................except(Exception1[, Exception2[,...ExceptionN]]]): 发生以上多个异常中的一个,执行这块代码 ......................else: 如果没有异常执行这块代码
- try...finally statement: The final code will be executed regardless of whether an exception occurs
# -*- coding: UTF-8 -*- try: fh = open("a.txt",‘w‘) fh.write("This is a file for Exception test!")finally: print "Error: File not found or access error"
Output:
[email protected]:~/code$ python test.py Error: File not found or access errorTraceback (most recent call last): File "test.py", line 3, in <module> fh = open("a.txt",‘w‘)IOError: [Errno 13] Permission denied: ‘a.txt‘[email protected]:~/code$ chmod +w a.txt [email protected]:~/code$ python test.py Error: File not found or access error
- Exception parameters: An exception can be taken with parameters, which can be used as an exception parameter for output
try: 正常的操作 ......................except ExceptionType, Argument: 你可以在这输出 Argument 的值...
Instance:
# -*- coding: UTF-8 -*- def temp_convert(var): try: return int(var) except ValueError,Arg: print "参数不包含数字:",Argprint temp_convert(‘xyz‘)
Output:
[email protected]:~/code$ python test.py 参数不包含数字: invalid literal for int() with base 10: ‘xyz‘None
To trigger an exception:
raise [Exception [, Args [, Traceback]]
The Exception statement is either of the exception type (for example, nameerror) parameter standard exception, and args is a self-supplied exception parameter.
# -*- coding: UTF-8 -*-def mye(level): if level < 1: raise Exception,"Invalid Error!" #触发异常后,后面的代码>将不会被执行try: mye(0)except Exception,err: print 1,errelse: print 2
Output:
[email protected]:~/code$ python test.py 1 Invalid Error!
- User-defined exceptions
By creating a new Exception class, programs can name their own exceptions. Exceptions should be typical of inheriting from the exception class, either directly or indirectly.
- The following are examples of RuntimeError-related instances in which a class is created and the base class is RuntimeError, which is used to output more information when the exception is triggered;
- In the TRY statement block, after the user-defined exception executes the EXCEPT block statement, the variable e is used to create an instance of the Networkerror class.
# -*- coding: UTF-8 -*-class NetworkError(RuntimeError): def __init__(self, arg): self.args = argtry: raise NetworkError("Bad hostName")except NetworkError,e: print e.args
Output:
[email protected]:~/code$ python test.py (‘B‘, ‘a‘, ‘d‘, ‘ ‘, ‘h‘, ‘o‘, ‘s‘, ‘t‘, ‘N‘, ‘a‘, ‘m‘, ‘e‘)
Question: Why output a single letter? I'll answer later.
Python Exception 2018-08-01