Python Learning-Basics-Exception handling

Source: Internet
Author: User

Abnormal:
    • Exception (Exception): Occurs because of a run-time error, resulting in a traceback
    • "Traceback" is a detailed description of the run-time errors that occur
Common exceptions: (To be perfected)
    • ValueError occurs when data does not conform to the expected format
    • Ioerroe occurs when data is not properly accessed (for example, your data file may be moved or renamed)
    • Nameerror, the name of the variable being called does not exist
Handling Exceptions:
    • The Try/except statement provides an exception handling mechanism to protect some code that might cause a run-time error
    • The pass statement is a Python empty statement or a null statement, and it does nothing

Such as

Try

Code #可能出现异常需要保护的语句 (can be multiple lines)

Except: #冒号前可以加具体的error名称 to exclude specific exceptions, such as ValueError

Pass #如果出现一个运行时错误, or execute the statement (whatever happens at run time, the Try statement catches all exceptions and processes, ignoring the error with pass)

Finally
1 Try:2     Print('ABC')3     Print(ABC)#There is no variable ABC, so it will be reported here Namevalue4     Print('1')#The above encountered an exception, will not execute this line, directly execute the contents of except after5 exceptNameerror:6     Pass7 finally:8     Print('2')#whether the code between try/except runs correctly or if an exception occurs, the finally group is executed, regardless of whether the exception is nameerror or not, the contents of the finally group will always run. 

Output:

ABC2
Show the wrong content

The above code does not show what really happened.

Try:    Print('ABC')    Print(ABC)Print('1')exceptNameerror as ERR:#assigning error content to variable str    Print('Error is', str (ERR))#to add STR to convert the type of err to a stringfinally:    Print('2')

Output:

 is ' ABC '  is  not defined2

Python Learning-Basics-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.