Fifth. exception handling in Python

Source: Internet
Author: User

Each programming language will have its own exception handling mechanism, although each has its own characteristics, but basically all the same, so what is the powerful exception handling mechanism in Python?

First, exception:

Python uses an exception object to represent an exception, and an exception is thrown when an error is encountered. If the exception object is not handled or captured, the program terminates execution with backtracking:

1 >>> 1/02Traceback (most recent call last):3   " <stdin> "  in <module>4or modulo by zero

In fact, each exception is an instance of a class that can be thrown and can be snapped in many ways, so that the program can catch the error and handle it instead of having the entire program fail. The more common exceptions are listed below:

Second, catch the exception and deal with

1, using Try/except for exception handling, the syntax is as follows:

Try

Program block

Except (Exception Class 1, Exception Class 2 ...)

Processing statements

else: #没有异常时执行

Program block

Finally: #都要执行, typically used to close files, database connections, and so on.

Processing statements

1>>>Try:2... x = input ("First number :")     3... y = input ("Second:")4...Printx/y5...exceptZerodivisionerror:6...Print("Division not Zero")7 ... 8First Number:109 second:0TenDivision notZero

2, abnormal full capture

Except does not follow any objects, but is not recommended.

Fifth. exception handling in Python

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.