** * 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. ** **
◆raise
raise IndexError('test error')
result
Traceback (most recent call last):
File "/~~~", line 1, in <module>
raise IndexError('test error')
IndexError: test error
You can use raise
to cause the specified error.
class UppercaseError(Exception):
pass
def check():
words = ['APPLE', 'orange', 'banana']
for word in words:
if word.isupper():
raise UppercaseError(word)
check()
result
Traceback (most recent call last):
File "/~~~", line 10, in <module>
check()
File "/~~~", line 8, in check
raise UppercaseError(word)
__main__.UppercaseError: APPLE
In this way, you will be able to generate your own errors in the program.
class UppercaseError(Exception):
pass
def check():
words = ['APPLE', 'orange', 'banana']
for word in words:
if word.isupper():
raise UppercaseError(word)
try:
check()
except:
print('This is my fault. Go next.')
result
This is my fault. Go next.
This way, when an error occurs in the process, "This isn't the default Python error, it's an error I made." It is convenient for development because it can be recognized as.
Recommended Posts