** * This article is from Udemy "[Introduction to Python3 taught by active Silicon Valley engineers + application + American Silicon Valley style code style](https://www.udemy.com/course/python-beginner/" Introduction to Python3 taught by active Silicon Valley engineers + application + American Silicon Valley style code style ")" It is a class notebook for myself after taking the course of. It is open to the public with permission from the instructor Jun Sakai. ** **
l = [0, 1, 2]
i = 5
try:
print(l[i])
except:
print('Error!')
result
Error!
If you try to do what you write in try:
and it fails due to some error
The processing in ʻexcept:` is executed.
l = [0, 1, 2]
del l
try:
print(l)
except IndexError as ex:
print('Error massage: {}'.format(ex))
except NameError as ex:
print('Error massage: {}'.format(ex))
result
Error massage: name 'l' is not defined
If it is ʻIndexError, this process, You can also specify the type of error, such as this process if it is
NameError`.
◆finally:
l = [0, 1, 2]
i = 5
try:
print(l[i])
except:
print('Error!')
finally:
print('clean up')
result
Error!
clean up
The process written in finally:
is always executed regardless of whether try succeeds or except.
l = [0, 1, 2]
i = 5
try:
print(l[i])
finally:
print('clean up')
result
clean up
Traceback (most recent call last):
File "/~~~", line 5, in <module>
print(l[i])
IndexError: list index out of range
Therefore, even if an error actually occurs, the processing in finally
will be executed first, and then the program will stop with an error.
◆else:
l = [0, 1, 2]
try:
print(l[0])
except:
print('Error!')
else:
print('done')
result
0
done
With ʻelse:, the processing in ʻelse:
is executed only if the processing in try:
is successful.
Recommended Posts