1
l = [1, 2, 3]
i = 5
print('start')
try:
l[0]
except IndexError as ex:
print('There is no such index.{}'.format(ex))
except NameError as ex:
print('Not defined.{}'.format(ex))
except Exception as ex:
print('other: {}'.format(ex))
else:
print("It was processed normally.")
finally:
print("end")
Execution result of 1
start
It was processed normally.
end
No error occurs, so The else block and finally block were executed.
2
l = [1, 2, 3]
i = 5
print('start')
try:
l[i]
except IndexError as ex:
print('There is no such index.{}'.format(ex))
except NameError as ex:
print('Not defined.{}'.format(ex))
except Exception as ex:
print('other: {}'.format(ex))
else:
print("It was processed normally.")
finally:
print("end")
Execution result of 2
start
There is no such index. list index out of range
end
Even though the index is only up to 2 Specify index 5 and IndexError occurs. So The except IndexError as ex block and the finally block were executed.
3
l = [1, 2, 3]
i = 5
del l
print('start')
try:
l[0]
except IndexError as ex:
print('There is no such index.{}'.format(ex))
except NameError as ex:
print('Not defined.{}'.format(ex))
except Exception as ex:
print('other: {}'.format(ex))
else:
print("It was processed normally.")
finally:
print("end")
Execution result of 3
start
Not defined. name'l' is not defined
end
Since l is gone with del l NameError occurs. So The except NameError as ex block and the finally block were executed.
4
l = [1, 2, 3]
i = 5
print('start')
try:
l + ()
except IndexError as ex:
print('There is no such index.{}'.format(ex))
except NameError as ex:
print('Not defined.{}'.format(ex))
except Exception as ex:
print('other: {}'.format(ex))
else:
print("It was processed normally.")
finally:
print("end")
Execution result of 4
start
other: can only concatenate list (not "tuple") to list
end
Since the list and tuple are added, An error that is neither IndexError nor NameError occurs. So The except Exception as ex block and the finally block were executed.
Recommended Posts