Python Learning Notes exception handling (vii)

Source: Internet
Author: User
Tags finally block throw exception

Exception handling

Exception handling is the work of writing code must be completed, for the operation does not meet the expected, the program will always be abnormal situation, and the exception can be properly handled, is to ensure the stability of the program is the key.

>> f = input ("filename")
filename/hone/a.py
>> ff = open (f)
Traceback (most recent):
File "<stdin>", line 1, in <module>
Filenotfounderror: [Errno 2] No such file or directory: '/hone/a.py '

The above code, the user input file does not exist, the system throws the file does not have an exception, the type is filenotfounderror.

There are many Python exception types, and the common types are as follows:

    • Nameerror: Access to an undefined variable
    • SyntaxError: Grammatical errors, strictly speaking, are procedural errors.
    • Indexerror: For a sequence, access to the index operation range
    • Keyerror: Access a non-existent dictionary key
    • ValueError: Invalid parameter passed in
    • Attribueerror: Accessing a property that does not exist in a class object

Exception handling

If an exception occurs, we can not throw the exception directly to the user, we should use Python's exception handling method to catch and handle the exception, the processing method is try,except,finally three keywords.

try:    有可能抛出异常的代码except 异常类型名称:    处理代码except 异常类型名称:    处理代码

Source: Laboratory Building
Links: https://www.shiyanlou.com/courses/1013
The content of this course, published by the author authorized experimental building, without permission, no reprint, download and illegal dissemination

Except can have multiple, each dealing with different types of exceptions, or without writing any exception type names, then all caught exceptions will be processed.

The above code uses exception handling improvements:

>> filename = input (' filename ')
filename/home/a.py
>> Try:
... f = open (filename)
.. print (F.read)
... f.close ()
... except Filenotfounderror:
.. print (' File not found ')
...
File not found

The finally keyword is used to clean up work, often with except, that is, whether it is normal or abnormal, the code inside the finally block will execute.
If an exception occurs in a file-handling program when F.write () writes data to a file, the close operation cannot be performed, and finally can be used to ensure that the contents of the finally block are executed regardless of whether the code in the try code block throws an exception. Ensure that the file is closed properly.

Modify the above program as follows, change to write operation, introduce finally guarantee file can be shut down normally:

filename = ‘/etc/protocols‘f = open(filename)try:    f.write(‘shiyanlou‘)except:    print("File write error")finally:    print("finally")    f.close()

The results of the program run:

File Write Error
Finally

Represents an exception, but still executes to the finally block of code.

The reason for throwing an exception here is to open a file in read-only mode, but attempt to write to the file, so an exception is thrown. Another except: This statement does not write any arguments, indicating that all exceptions thrown in the try code block will be processed.

Throw exception
What if we want to throw some exceptions during the execution of the program? You can use the Raise statement.

Raise Exception Name
For example, we want to throw a valueerror in the code and use it directly:

Raise ValueError ()
The external code can be captured and processed using the except ValueError.

Python Learning Notes exception handling (vii)

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.