First encounter with Try-except (Core Python programming 2nd Edition 3.6)

Source: Internet
Author: User
Tags throw exception

1 #coding:utf-8 # using Windows system, first line ' #!/usr/bin/env Pyton ' useless, all changed to ' # Coding:utf-8 '
2 3 'readtextfile.py--Read and display text file'4 5 #get filename6fname = Raw_input ('Enter FileName:')7 Print8 9 #attempt to open file for readingTen Try: OneFobj = open (fname,'R') # Try to open fname A exceptIOError, E:#The detailed cause of the captured IOError error is placed in Object E, and then the except code block that runs the exception (can also be written as ' except IOError as e: ') - Print "* * * File Open error:", E # print exception information - Else: # If the try has no errors, execute the Else statement the #Display contents to the screen - forEachlineinchFobj: - PrintEachline, # Comma is to resist the print statement automatically generated line terminator (FName inside itself has a line terminator, if you do not add a comma, there will be a blank line between the printed content) -Fobj.close ()
Keywords related to python exceptions:
Keyword keyword          description
Raise           throw/Throw exception
Try/except      catching exceptions and handling
Pass            ignores exceptions
As              definition exception instance (except IOError as E)
Finally         code that executes regardless of whether an exception occurs
Else            If the statement in the try does not throw an exception, the statement in the else is executed

First encounter with Try-except (Core Python programming 2nd Edition 3.6)

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.