Come and see the try/except exception handling in Python, it is really nice

Preface

This article analyzes the usage of exception handling try/except/finally/raise in Python. Share it for your reference, the specifics are as follows:
An exception occurs during the execution of the program. If python cannot handle the program normally, an exception will occur, causing the entire program to terminate execution. Use try/except statements in python to catch exceptions.

try/except

There are many types of exceptions. You can use Exception to catch all exceptions when you are not sure of the type of exception that may occur:

try:
	pass
except Exception as e:
 print(e)

try/except/else

An else statement can also be followed by the try statement, so that when the try statement block is executed normally without exception, the content after the else statement will be executed:

try:
	pass
except Exception as e:
 	print("No exception")
else:
    print("我打印的是else")

try/Except/finally

After the try statement is followed by a finally statement, regardless of whether an exception occurs in the try statement block, the content after the finally statement will be executed after the try is executed:

try:
  pass
except Exception as e:
  print("Exception: ", e)
finally:
  print("try is done")

raise an exception

Use raise to throw an exception:

a = 0
if a == 0:
  raise Exception("a must not be zero")

It is best to point out the specific type of exception, such as:

a = 0
if a == 0:
  raise ZeroDivisionError(``"a must not be zero"``)

Here I recommend a software testing exchange group I created by myself, QQ: 642830685. The group will share software testing resources, test interview questions and testing industry information from time to time. Everyone can exchange technology together in the group, and there are big guys to answer questions for you.

Guess you like

Origin blog.csdn.net/weixin_53519100/article/details/112972561