Python learning - exceptions

巴扎黑
Release: 2016-12-09 14:05:16
Original
1351 people have browsed it

的 Exception

When some abnormal conditions appear in your program, abnormalities occur. For example, when you want to read a certain file, and that file does not exist. Or you accidentally deleted it while the program was running. The above situations can be handled using exceptions.

           What will happen if there are some invalid statements in your program? Python will handle situations like this by raising and telling you there's an error.

try..except

      1. Handle exceptions

                                                                                                            ‐ out 1. Handle exceptions
                ‐ outs out of ’s 1. Handle exceptions to be handled with try..except statement-. We put our normal statements in try-blocks and our error handling statements in except-blocks.
An example of handling exceptions is as follows:

import sys
try:
    s = raw_input('Enter something --> ')
except EOFError:
    print '\nWhy did you do an EOF on me?'
    sys.exit()
except:
    print '\nSome error/exception occurred.' 
print 'Done'
Copy after login

Output:

Python code

Enter something --> +  
Done
Copy after login

We put all statements that may cause errors in try blocks, and then handle all errors and exceptions in except clauses/blocks.从 Except clauses can specifically handle single errors or abnormalities, or a set of errors/abnormalities included in parentheses. If no error or exception name is given, it will handle all errors and exceptions. For every try clause, there is at least one associated except clause.
        If an error or exception is not handled, the default Python handler will be called. It will terminate the program and print a message, which we have already seen done.
You can also associate the try..catch block with an else clause. When no exception occurs, the else clause will be executed.

2. Raise an exception
We can also get the exception object to get more information about this exception.
You can use the raise statement to raise an exception. You also have to specify the name of the error/exception and the exception object that was triggered with the exception. The errors or exceptions you can raise should be a direct or indirect derived class of the Error or Exception class respectively.
An example of how to raise an exception is as follows:

class ShortInputException(Exception):
    '''A user-defined exception class.'''
    def __init__(self, length, atleast):
        Exception.__init__(self)
        self.length = length
        self.atleast = atleast
try:
    s = raw_input('Enter something --> ')
    if len(s) < 3:
        raise ShortInputException(len(s), 3)
except EOFError:
    print &#39;\nWhy did you do an EOF on me?&#39;
except ShortInputException, x:
    print &#39;ShortInputException: The input was of length %d, \
          was expecting at least %d&#39; % (x.length, x.atleast)
else:
    print &#39;No exception was raised.&#39;
Copy after login

Output:

Python code

Enter something --> 2222  
No exception was raised.  
Enter something --> 1  
ShortInputException: The input was of length 1,           was expecting at least 3
Copy after login

Here, we have created our own exception type, in fact we can use any predefined exception/error. This new exception type is the ShortInputException class. It has two fields: length is the length of the given input, and atleast is the minimum length expected by the program.

            In the except clause, we provide the error class and variables used to represent the error/exception object. This is similar to the concept of formal parameters and actual parameters in function calls. In this particular except clause, we use the length and atleast fields of the exception object to print an appropriate message to the user.


try..finally

If you are reading a file and want to close the file regardless of whether an exception occurs, what should you do? This can be done using finally block. Note that you can use both an except clause and a finally block within a try block. If you want to use them at the same time, you need to embed one into the other.

The example of using finally is as follows:

import time
f = file(&#39;poem.txt&#39;)
try:  
    while True:
        line = f.readline()
        if len(line) == 0:
            break
        time.sleep(2)
        print line,
finally:
    f.close()
    print &#39;Cleaning up...closed the file&#39;
Copy after login

Output:

Python code

Programming is fun  
When the work is done  
if you wanna make your work also fun:  
        use Python!  
Cleaning up...closed the file
Copy after login
We carry out the usual file reading work, but I intentionally use the time.sleep method to pause for 2 seconds before printing a line. The reason for this is to make the program run slower (Python usually runs very fast due to its nature). While the program is running, press Ctrl-c to interrupt/cancel the program. We can observe that the KeyboardInterrupt exception is triggered and the program exits. But before the program exits, the finally clause is still executed and the file is closed.


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template