Concise python tutorial Nine----exceptions

Source: Internet
Author: User
Tags export class finally block

Use the Try...except statement to handle the exception. We put the usual statements in the try-block, and the error-handling statements in the except-block.

Import SYS Try :     = Raw_input ('Enter something-->') except Eoferror:    '\nwhy Did you do a EOF on me? '     sys.exit () except:    print'\nsome error/exception occurred. '  'done'

Results:

==================== restart:d:/python_test/pickling.py ====================Enter something -   do a EOF on me?>>> ==================== restart:d:/python_test/pickling.py ================== = =Enter something---Done

Put all the statements that could throw the error in the try block, and then handle all the errors and exceptions in the EXCEPT clause/block.

Except clauses can be specialized in handling a single error or exception, or a set of errors/exceptions that are included 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.

You can also make try. The catch block is associated with the last else clause. When no exception occurs, the ELSE clause is executed.

To throw an exception:

You can use the raise statement to throw an exception, you need to indicate the name of the error/exception and the exception object that accompanies the exception. The errors and exceptions you can throw should be a direct or indirect export class for the error or exception class, respectively.

classshortinputexception (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-->')    ifLen (s) <3: Raise Shortinputexception (Len (s),3) except Eoferror:print'\nwhy did you do a 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.'

Results:

==================== restart:d:/python_test/pickling.py ====================Enter something -   do a EOF on me?>>> ==================== restart:d:/python_test/pickling.py ================== = =Enter something--2,        3>>> ==================== restart:d:/ python_test/pickling.py ====================Enter somethingtoAbcno exception was raised.

Try...finally

If you are reading a file, you want to close the file regardless of whether the exception occurred or not. We can do this by using the finally block.

Note that under a try block, you can use both the EXCEPT clause and the finally block at the same time, and when you use them, you need to embed one in the other

Import TimeTry: F=file ('Poem.txt')     whileTrue:line=F.readline ()ifLen (line) = =0:             BreakTime.sleep (2) Print line,finally: F.close () print'cleaning up...closed The file'

Results:

IS wasdone  if you wanna make your work also Fun:use Python! cleaning up...closed The file

Description: Pauses for 2 seconds with the Time.sleep method before each line is printed. While the program is running, press Ctrl-c to break/Cancel the program.

We can see this again:

Programming is Funwhen the work was donecleaning up...closed the Filetraceback (most recent call last):  File "D:/python _test/pickling.py ", line up, in <module>    time.sleep (2) Keyboardinterrupt

The keyboardinterrupt exception is triggered and the program exits. But before the program exits, the finally clause is still executed, closing the file

Concise python tutorial Nine----exceptions

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.