[PYTHON] Catch multiple types of exceptions

1


import sys, traceback

number1 = 100
number2 = 'a'

print('strat')

try:
    answer = number1 / number2
    print(answer)
except ZeroDivisionError as e:
    print('It does not break at 0.')
    sys.stderr.write(traceback.format_exc())
except NameError as e:
    print('Calling an undefined variable')
    sys.stderr.write(traceback.format_exc())
except Exception as e:
    print('An unexpected error has occurred.')
    sys.stderr.write(traceback.format_exc())
finally:
    print('end')

Execution result of 1


strat
An unexpected error has occurred.
end

1 run-time error


Traceback (most recent call last):
  File "Main.py", line 9, in <module>
    answer = number1 / number2
TypeError: unsupported operand type(s) for /: 'int' and 'str'

Since number2 ='a', TypeError has occurred.

TypeError is except ZeroDivisionError、 It cannot be captured by except NameError, Can be caught with except Exception.

Exception is a superclass of ZeroDivisionError and NameError. To put it the other way around It is a subclass of ZeroDivisionError and NameError.

Exception can catch all exceptions, Subclasses are a more specific exception.

When catching multiple exceptions It is checked whether there is a corresponding except block in order from the top. For that reason, You need to start with a more specific subclass.

Otherwise, The except Exception block, which catches all exceptions, Before the subclasses that can catch exceptions more specifically move It catches an exception.

2


import sys,traceback

number1 = 100
number2 = 0

print('start')

try:
    answer = number1 / number2
    print(answer)
except Exception as e:
    print('An unexpected exception has occurred.')
    sys.stderr.write(traceback.format_exc())
except ZeroDivisionError as e:
    print('It does not break at 0.')
    sys.stderr.write(traceback.format_exc())
except NameError as e:
    print('You called an undefined variable.')
    sys.stderr.write(traceback.format_exc())
finally:
    print('end')

Execution result of 2


strat
An unexpected error has occurred.
end

2 run-time error


Traceback (most recent call last):
  File "Main.py", line 9, in <module>
    answer = number1 / number2
ZeroDivisionError: division by zero

I wanted to output "0 does not break", but Because the superclass Exception catches any exception The except Exception block has caught an exception.

Recommended Posts

Catch multiple types of exceptions
Review of exceptions
Multiple inheritance of classes
Copy of multiple List
Types of interprocess communication
Types of recommendation systems
Revenge of the Types: Revenge of types
Sum of multiple numpy arrays (sum)
Summary of Linux distribution types
Optimal placement of multiple images
Install multiple versions of Python
[ev3dev × Python] Control of multiple motors
I summarized 11 types of operating systems
Manage multiple types of users with CustomUser in django-allauth (multi type user)