Python Learning--exceptions

Source: Internet
Author: User
Abnormal

The exception occurs when there are some abnormal conditions in your program. For example, when you want to read a file, and that file does not exist. Or when the program is running, you accidentally delete it. These conditions can be handled using exceptions.
What if there are some invalid statements in your program? Python throws and tells you that there is a bug that can handle this situation.

Try: Except

1. Handling Exceptions
We can use try: The except statement to handle the exception. We put the usual statements in the try-block and put our error-handling statements in the except-block.
Examples of handling exceptions are as follows:

Import Systry:    s = raw_input (' Enter something--and ') except Eoferror:    print ' \nwhy did you do a EOF on me? '    sys.exit () except:    print ' \nsome error/exception occurred. ' Print ' done '

Output:

Python code

Enter something--+ done  

We put all the statements that could throw errors in the try block, and then handle all the errors and exceptions in the EXCEPT clause/block. The
except clause can handle a single error or exception, or a set of errors/exceptions that are enclosed in parentheses. If the name of the error or exception is not given, it handles all errors and exceptions. For each try clause, there is at least one associated except clause.
If an error or exception is not handled, the default Python processor is called. It terminates the operation of the program and prints a message that we have seen in this process. The
can also let try: The catch block is associated with the last else clause. When no exception occurs, the ELSE clause is executed.

2. Throws an exception
we can also get the exception object to get more information with this exception. The
can throw an exception using the Raise statement. You also have to indicate the name of the error/exception and the exception object that accompanies the exception firing. The error or exception that you can throw should be a direct or indirect export class of error or Exception class, respectively. The
example of how to throw 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-to ')    if Len (s) < 3:        raise Shortinputexception (Len (s), 3) Except Eoferror:    print ' \nwhy did I do a EOF on me? ' Except Shortinputexception, x:    print ' shortinputexception:the input was of length%d, \ is          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, is           expecting at least 3

Here, we create our own exception types, and we can actually use any predefined exceptions/errors. This new exception type is the Shortinputexception class. It has two fields: length is the size of the given input, and atleast is the minimum length the program expects.
In the EXCEPT clause, we provide the error class and the variables used to represent the error/exception object. This is similar to the concept of formal parameters and arguments in function calls. In this particular except clause, we use the length and atleast fields of the exception object to print an appropriate message for the user.

Try: Finally

If you are reading a file, you want to close the file regardless of whether the exception occurred or not, how to do it? This can be done using the finally block. Note that under a try block, you can use both the EXCEPT clause and the finally block. If you want to use them at the same time, you need to embed one in the other.
Use the finally example 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, the work was done  if you wanna make your work also fun: Use          python!  Cleaning up...closed The file

We do the usual work of reading the file, but I intentionally paused for 2 seconds with the Time.sleep method before each line printed. The reason for this is to make the program run slower (Python usually runs fast because of its nature). When the program is running, press Ctrl-c to break/Cancel the program. We can observe that the keyboardinterrupt anomaly is triggered and the program exits. But before the program exits, the finally clause is still executed and the file is closed.

  • 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.