A concise introduction to exception handling in Python _python

Source: Internet
Author: User
Tags assert exception handling

The python exception handling mechanism is similar to Java, using a try-except-finally structure.

Try-except Detection exception

Format

Copy Code code as follows:

Try
Try_statement
Except (ErrorType1, ErrorType2), E:
Handle_statement
Finally
Finally_statement

Instance
Copy Code code as follows:

#!/usr/bin/python
Try
A=12
B=0
c = A/b
Except Exception, E:
Print "Exception occurs:", E
Finally
Print "Finally handle!"

Context Manager (With...as ...) Statement)

The WITH statement can be especially useful when you first open the scenario where the resource was last freed, because it automatically frees up the resources that are in the possession and does not need to be shown to release the resources

Format

Copy Code code as follows:

With context_expr [as Var]:
With_statement

raise throws an exception

Format

Copy Code code as follows:

Raise exception[, args] or raise Exception (args)

Instance
Copy Code code as follows:

Raise Exception (' exampleexception ')

assert

Detects the key point of the program, the assertion is unsuccessful when the trigger Asserterror (assertion error)
Format is as follows

Copy Code code as follows:

Assert expression[, arguements]

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.