The difference between Python raise and assert

Source: Internet
Author: User
Tags assert

Differences between raise and assert in Python one, throwing exceptions using raise

Python can automatically trigger an exception, raise ( built-in function ) is defined as the thrown exception that is displayed, the user can use raise to judge, explicitly throw an exception , raise execution after the program will no longer execute down.

Type example:

#!/usr/bin/env python#-*-coding:utf-8-*-__author__ = ' 40kuai ' books_dict = {' name ': ' Python ', ' pages ': 390}key = input (' View Properties: ') if key in Books_dict:    print (Books_dict[key]) Else:    

Raise can also create custom exceptions for users

#!/usr/bin/env python#-*-coding:utf-8-*-__author__ = ' 40kuai ' class Helei (Exception):  # inherit Exception    def __ Init__ (Self, msg):        self.message = msg    def __str__ (self):  # executed when called by print, can not write        return Self.messageif __ name__ = = ' __main__ ':    try:        raise Helei (' My Exception ')  # Trigger exception    except Helei as E:        print (e)
Ii. use of Assert

The Assert statement is used to detect whether a conditional expression is true. An Assert statement, also known as an assertion statement, asserts that an expression detected by Assert is always true.

An assertion is used to specify that an operation must be true. You can also skip assert detection by adding the python-o parameter when the script executes.

You can use assert False to show that code writing is not complete

The difference between Python raise and assert

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.