Concise Python Tutorial Learn note 9

Source: Internet
Author: User
Tags export class

13. Abnormal

(1) Error

Some invalid statements in the program, such as syntax errors, are as follows:

1 " AA " 2 syntaxerror:invalid Syntax 3 Print " AA " 4 AA 5

(2) Try...except

1>>> s = raw_input ("Enter something --")2Enter something--and #这里期望输入, but the actual execution of Ctrl+d causes the following exception3 4 Traceback (most recent):5File"<pyshell#4>", Line 1,inch<module>6s = raw_input ("Enter something --")7 eoferror:eof When reading a line8>>>

You can use Try...except to handle exceptions

1 #-*-coding:utf-8-*-2 3 ImportSYS4 5 Try:6s = raw_input ("Enter something --")7 exceptEoferror:8     Print "\nwhy did yo do a EOF on me?"9Sys.exit ()#Exit The programTen except: One     Print "\nsome error/exception occurred." A     #Here , we aren't exiting the program -  - Print " Done"

Output:

(3) Exception thrown

You can use a raise statement to throw an exception .

Also specify the name of the error/exception and the exception object that accompanies the exception.

The error or exception that can be thrown should be Error a Exception direct or indirect export class of one or class.

1 #-*-coding:utf-8-*-2 3 4 classshortinputexception (Exception):5     """A user-defined Exception class."""6 7     def __init__(self, length, atleast):8Exception.__init__(self)9Self.length =lengthTenSelf.atleast =atleast One  A  - Try: -s = raw_input ("Enter something --") the     ifLen (s) < 3: -         Raise Shortinputexception (Len (s), 3) -         #Other work can continue as usual here - exceptEoferror: +     Print "\nwhy did you do a EOF on me?" - exceptshortinputexception, x: +     Print "shortinputexception:the input was of length%d,was expecting at least%d"%(X.length, X.atleast) A Else: at     Print "No exception was raised."

Output:

(4) try...finally

Do you want to do something without exception or not?

This can be finally done using blocks.

Concise Python Tutorial Learn note 9

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.