Python Throw Exception of raise Knowledge Point Summary

  • 2021-11-13 02:19:56
  • OfStack

The try block in Python can catch errors in the test code block. The except block can handle errors. The finally block can execute code regardless of the results of the try-and except blocks. This article mainly introduces Python throwing throw exception (raise).

Python Common Terms

Throw Throw Exception (raise)

As an Python developer, you can throw exceptions in some cases.

To throw (or throw) an exception, use the raise keyword.

For example:

When x is less than 0, throw an exception and stop the program:


x = -1

if x < 0:
    raise Exception("x Need to be greater than or equal to 0 The number of ")

The raise keyword is used to throw an exception.

You can define which errors are raised and display text to the user.

For example:

If x is not an integer, TypeError is thrown:


x = "hello"

if not type(x) is int:
    raise TypeError(" Only integers are allowed ")

Instance extension:


try:
  s = None
  if s is None:
    print("s  Is an empty object ")
    #  If you throw a NameError Exception, the following code will not execute 
    raise NameError
  #  This sentence will not be executed, but the following one except Or will you go to 
  print(len(s))
except TypeError:
  print(" Empty object has no length ")
 
s = None
if s is None:
  raise NameError
#  If you do not use try......except In this form, the exception is thrown directly and will not be executed here 
print("is here?")

Related articles: