Python Exception 2018-08-01

Source: Internet
Author: User

    1. 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!
    1. Use exceptions without any exception type
try:    正常的操作   ......................except:    发生异常,执行这块代码   ......................else:    如果没有异常执行这块代码
    1. Using exceptions with multiple exception types
try:    正常的操作   ......................except(Exception1[, Exception2[,...ExceptionN]]]):   发生以上多个异常中的一个,执行这块代码   ......................else:    如果没有异常执行这块代码
    1. 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
    1. 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
    1. 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!
    1. 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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.