Python learning-exception

Source: Internet
Author: User
An exception occurs when some exceptions occur in your program. For example, if you want to read a file that does not exist. Or you accidentally delete it when running the program. Exceptions can be used to handle the above situations. What if your program has some invalid statements? Python will cause and tell you there is an error to handle this situation. Try... handle T1. handle exceptions... exceptions

An exception occurs when some exceptions occur in your program. For example, if you want to read a file that does not exist. Or you accidentally delete it when running the program. Exceptions can be used to handle the above situations.
What if your program has some invalid statements? Python will cause and tell you there is an error to handle this situation.

Try... try T

1. handling exceptions
We can use the try... try T statement to handle exceptions. We place the common statements in the try-block and the error handling statement in the fail T-block.
An example of exception handling is as follows:

import systry:    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'

Output:

Python code

Enter something --> +  Done

We place all statements that may cause errors in the try block, and then process all errors and exceptions in the limit T clause/block.
The limit T clause can specifically handle a single error or exception, or a group of errors/exceptions included in parentheses. If no error or exception name is provided, it will handle all errors and exceptions. Each try clause must have at least one correlated limit T clause.
If an error or exception is not processed, the default Python processor is called. It will terminate the running of the program and print a message. we have seen this process.
You can also associate the try... catch block with the previous else clause. When no exception occurs, the else clause is executed.

2. exception
We can also obtain the exception object to obtain more information about this exception.
You can use the raise statement to raise an exception. You must also specify the error/exception name and the exception object triggered with the exception. The errors or exceptions you can cause should be a direct or indirect export class of the Error or Exception class.
An example of how to cause 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 = atleasttry:    s = raw_input('Enter something --> ')    if len(s) < 3:        raise ShortInputException(len(s), 3)except EOFError:    print '\nWhy did you do an EOF on me?'except ShortInputException, x:    print 'ShortInputException: The input was of length %d, \          was expecting at least %d' % (x.length, x.atleast)else:    print 'No exception was raised.'

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

Here, we have created our own exception types. In fact, we can use any predefined exceptions/errors. The 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 limit T clause, we provide error classes and variables used to indicate error/exception objects. This is similar to the concept of form parameters and real parameters in function calls. In this special limit T clause, we use the length and atleast fields of the exception object to print an appropriate message for the user.

Try .. finally

What should you do if you want to close the file regardless of whether an exception occurs? This can be done using finally blocks. Note: in a try block, you can use the limit T clause and the finally block. If you want to use them at the same time, you need to embed one into another.
The finally example is as follows:

import timef = file('poem.txt')try:      while True:        line = f.readline()        if len(line) == 0:            break        time.sleep(2)        print line,finally:    f.close()    print 'Cleaning up...closed the file'

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

We usually read files, but I tried to pause for 2 seconds by using the time. sleep method before each row is printed. The reason for doing so is to make the program run slowly (Python usually runs fast due to its nature ). When running the program, press Ctrl-c to interrupt/cancel the program. We can observe that the KeyboardInterrupt exception is triggered and the program exits. However, before the program exits, the finally clause is still executed to close the file.

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.