TypeError Example: TypeError: unsupported operand type (s) for /:'str' and'int' Error that occurs when trying to calculate the String type
ZeroDivisionError Example: ZeroDivisionError: division by zero Error that occurs when dividing by zero like 1/0
NameError Example: NameError: name'hoge' is not defined Error when using undefined variables
AttributeError Example: AttributeError: type object ‘list’ has no attribute ‘fuga’ Error when trying to access a non-existent attribute
--try
: Exception handling of enclosed code
--ʻExcept : Block to be executed when an error-case exception occurs --ʻExcept
: Block to execute when any exception occurs
--ʻElse: Block to execute only if no exception occurs --
finally`: Block to execute with or without an exception
try-except Used when you want to continue the process even if an error is derived from the executed process.
Num = [1,2,3]
n = 4
#Extract errors while continuing processing
try:
print(Num[n])
except:
print('error') #データがない場合、error
print('Continue processing')
#Output result
error
Continue processing
If there are multiple exceptions, the processing is divided according to the type of exception.
Num = [1,2,3,4]
n = 5
n = 'String'
try:
print(Num[n])
except IndexError as ie:
print('error contents: {}'.format(ie))
except NameError as ne:
print(ne)
except Exception as ex: #When an error other than IndexError and NameError occurs
print('error contents: {}'.format(ex))
print('Exception occurred')
#Output result
error contents: list indices must be integers or slices, not str
Exception occurred
finaly Even if an error occurs, always execute the following processing in finaly
Num = [1,2,3,4]
n = 5
n = 'String'
try:
print(Num[n])
except IndexError as ie:
print('error contents: {}'.format(ie))
except NameError as ne:
print(ne)
except Exception as ex: #When an error other than IndexError and NameError occurs
print('error contents: {}'.format(ex))
finally: #← Process that you definitely want to execute
print('Must be executed')
print('Exception occurred')
#Output result
error contents: list indices must be integers or slices, not str
Must be executed
Exception occurred
Use raise if you want to intentionally raise an error
try:
raise TypeError
except:
print('Intentionally generate an error')
Recommended Posts