Python exception detection and handling methods

  • 2021-01-06 00:40:22
  • OfStack

Catch exceptions


#  Use for numeric variables append operation 
a = 123
a.apppend(4)

When this program is executed, it throws:


AttributeError: 'int' object has no attribute 'apppend'

We use the try:except statement for the capture.


#  Catch exceptions 
a = 123
try:
  a.apppend(4)
except AttributeError:
   print(" Number types cannot be used append operation ")

The output is as follows:


 Number types cannot be used append operation 

Catch multiple exceptions


#  Catch exceptions 
a = 123
try:
  # a.apppend(4)
  print(1/0)
except AttributeError:
   print(" Number types cannot be used append operation ")
except ZeroDivisionError:
   print("0 It can't be a divisor ")

Output results:


0 It can't be a divisor 

It is also possible to place the exception to 1, as JDK1.7 does.


#  Catch exceptions 
a = 123
try:
  a.apppend(4)
  # print(1/0)
except (AttributeError,ZeroDivisionError) as e:
   print(" There is an error  %s" %e)

Put the exception type into a primitive. If you want to print specific exception information, you can rename the exception information and print it.

The output is as follows:


 There is an error  'int' object has no attribute 'apppend'

Use Exception to catch all exceptions


#  Catch exceptions 
a = 123
try:
  print(1/'kk')
except Exception as e:
   print(" There is an error  %s" %e)

Series 1 with Exception Capture, and the output results are as follows:


 There is an error  unsupported operand type(s) for /: 'int' and 'str'

Custom exception


AttributeError: 'int' object has no attribute 'apppend'
0

You can use the ES46en keyword and ES47en, and the output is as follows:


AttributeError: 'int' object has no attribute 'apppend'
1

finally statement


AttributeError: 'int' object has no attribute 'apppend'
2

The results are as follows:


 There is an error  division by zero
 perform finally

The finally statement will still be executed even if it is thrown once.

conclusion


Related articles: