Python exception handling and python exception handling

Source: Internet
Author: User

Python exception handling and python exception handling

1. What is an exception?
An exception occurs when a program encounters a bug or an error occurs during running. If a program fails normally, the program will be interrupted. If you do not want the program to be terminated, so you have to handle the exceptions. This is the meaning of the exceptions.

2. Exceptions include common exceptions, actively triggered exceptions, and custom exceptions.

The syntax structure of exception handling is as follows:

Str1 = 'A' try: # main logic processing code int (str1) handle T IndexError, e: # specify the exception information print "IndexError! "Failed t Exception, e: # This is a universal Exception capture print eelse: # passfinally: # If no Exception exists, pass is executed.

In addition to automatically triggering exceptions, we can also actively trigger exceptions. The structure is as follows:

Automatic trigger exception

Try: raise Exception ('error... ') failed t Exception, e: print e

Custom Exception (define a class that inherits from the Exception class and then define the _ str _ method to process the returned value)

Class myException (Exception): def _ init _ (self, msg): self. message = msg def _ str _ (self): return self. message try: raise myException ('My exception') failed t myException, e: print e

Assertions

Assert Condition

An error is returned only when the condition is true. Commonly Used for program debugging

 

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.