Brief introduction to exception handling in Python

Source: Internet
Author: User
This article describes how to handle exceptions in Python. This article describes how to detect exceptions in try-retry T and how to use the context manager (... As... Statement), raise raises exceptions, assertions, and so on. For more information, see The python exception handling mechanism. it is similar to java and uses the try-try T-finally structure.

Try-try T to detect exceptions

Format

The code is as follows:


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


Instance

The code is as follows:


#! /Usr/bin/python
Try:
A = 12
B = 0
C = a/B
Except t Exception, e:
Print "Exception occurs:", e
Finally:
Print "finally handle! "


Context manager (... As... Statement)

The with statement is particularly applicable to scenarios where the resource is first opened and finally released, because it automatically releases the occupied resources and does not need to be explicitly released.

Format

The code is as follows:


With context_expr [as var]:
With_statement


Raise exception

Format

The code is as follows:


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


Instance

The code is as follows:


Raise Exception ('exampleexception ')


Assertions

Checks the key points of the program. AssertError is triggered when the AssertError is unsuccessful)
The format is as follows:

The code is 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.