Python Exception handling

Source: Internet
Author: User

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.

1. Handling Exceptions

#!/usr/bin/python# Filename:try_except.pyimport systry:        s = raw_input (' Enter something--') except eoferror:< C1/>print ' \nwhy did you do a EOF on me? '        Sys.exit () # exit the programexcept:        print ' \nsome error/exception occurred. '        # Here, we aren't exiting the Programprint ' done '

Run results

#./try_except.py    enterenter something-->done#./try_except.py   ctrl+denter something-->why did it EOF on me?

2. How to throw an exception

#!/usr/bin/python# Filename:raising.pyclass 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) # Other work can continue as usual hereexcept Eoferr Or:        print ' \nwhy did you 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. '

Run results

[Email protected] python]#/raising.pyenter something--ffshortinputexception:the input was of length 2, was ExPEC Ting at least 3[[email protected] python]#./raising.pyenter something-222No exception was raised.

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 length of the given input, and atleast is the minimum length the program expects.

3. Use finally

#!/usr/bin/python# Filename:finally.pyimport timetry:        f = file (' Poem.txt ') while        True: # Our usual file-reading Idiom line                = F.readline ()                if len [line] = = 0: Break                Time.sleep (2)                print line,finally:        f.close ()        print ' Cleaning up...closed the file '

Run results

#./finally.pyprogramming is funwhen the work are doneif you wanna make your work also fun:use python! Cleaning up...closed The file#/finally.pyprogramming is funwhen the work is done^ccleaning up...closed the file      --ct Rl+c to Breaktraceback (most recent):  File "./finally.py", line ten, in <module>    time.sleep (2) Keyb Oardinterrupt

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, closing the file

Python Exception handling

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.