This article was automatically translated from Japanese using AI. The Japanese version is the authoritative version.
Errors sometimes come up when you are writing a program in Python.
Errors are actually helpful, since they tell you that your program has not been put together correctly,
but sometimes an error will stop your program from running altogether.
Sometimes code that is syntactically correct still raises an error at runtime.
An error raised when the syntax is grammatically incorrect is called a syntax error,
while an error that is grammatically correct but logically wrong is called an exception.
Some examples of exceptions:
・TypeError: the operands are of incompatible types
EX. word/2 , 4*number
・ZeroDivisionError: division by zero
EX. 3/0
・ValueError: the type is correct but the value is not appropriate
EX. int(“string”)
You can use conditional branching to head off errors before they happen and write a logically correct program, but you can also take the approach of handling the exception when an error does occur.
That is where try, except comes in.
try:
実行したい処理(例外を含むかもしれない)
except エラー名:
例外発生時に行う処理
You use it like this.
For example,
try:
print(10 / 0)
except ZeroDivisionError:
print('できませんでした')
#出力
できませんでした
That is the result.
Note, however, that except only catches the error you specify
(in this program, only ZeroDivisionError), so if any other error occurs it will still be reported as an error when the program runs.
When you expect more than one kind of error, add another “except ErrorName:” clause.
try:
print(10 / 0)
except ZeroDivisionError:
print('できませんでした')
except ValueError:
print('値がうまく合致しませんでした')
You can specify multiple except clauses.
If you leave out the exception name entirely in the except clause, you can catch every exception.
try:
print(10 / 0)
except:
print('できませんでした')
Be very careful with this, though: because it catches every exception, it will also hide errors the programmer never anticipated.
There are also keywords related to the try-except syntax that let you specify what happens after an exception occurs.
I will list them briefly here.
I plan to cover them in detail in another blog post.
- raise: deliberately raise an exception
- pass: do nothing after the exception occurs
- else: run only if no exception occurred
- finally: always run, whether or not an exception occurred
