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