A concise introduction to exception handling in Python

Source: Internet
Author: User
The python exception handling mechanism is similar to Java, using the try-except-finally structure.

Try-except Detecting anomalies

Format
Copy the Code code as follows:


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


Instance
Copy CodeThe code is 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 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
Copy the Code code as follows:


With context_expr [as Var]:
With_statement


raise throws an exception

Format
Copy the Code code as follows:


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


Instance
Copy CodeThe code is as follows:


Raise Exception (' exampleexception ')


Assertion

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


Assert expression[, arguements]
  • 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.