Python Exception handling

Source: Internet
Author: User

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

Try-except Detecting anomalies

Format

try:    try_statementexcept (ErrorType1, ErrorType2),e:    handle_statementfinally:    finally_statement

Instance

#!/usr/bin/pythontry:    a=12    b=0    c = a/bexcept Exception, e:    print  "Exception occurs: " , efinally:    print"finally handle!"
Context Manager (With...as ... Statement

The WITH statement can be especially useful for scenarios where the resource is finally freed up, because it automatically frees the owning resource and does not need to be displayed to release the resource

Format

with context_expr [asvar]:    with_statement
Raise throws an exception

Format

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

Instance

Raise Exception (' exampleexception ')

Assertion

Detecting key points of the program, triggering Asserterror (assertion error) when the assertion is unsuccessful
The format is as follows

Assert expression[, arguements]

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