try and except: Exception Handling in Python

This article was automatically translated from Japanese using AI. The Japanese version is the authoritative version.

Errors sometimes occur when writing programs in Python.
Errors are actually helpful, since they tell you that your program has not been put together correctly,
but there are times when an error stops your program from running at all.

Sometimes code is syntactically correct yet 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.

Examples of exceptions include:
・TypeError: the operands have 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 prevent errors before they occur and write logically correct programs by using conditional branching, but another option is to handle errors with exception handling when they do occur.

That is where try, except comes in.

try: 
    実行したい処理(例外を含むかもしれない)
except エラー名:
    例外発生時に行う処理

You use it like this.
For example,

try:
    print(10 / 0)
except ZeroDivisionError:
    print('できませんでした')
#出力
できませんでした

This is the result.
Note, however, that except only catches the errors you specify
(in this program, only ZeroDivisionError), so any other error 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 in the except clause, it will catch every exception.

try:
    print(10 / 0)
except:
    print('できませんでした')

However, because this catches every exception, it will also hide errors that the programmer never anticipated, so use it with great care.

There are also related keywords in 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 an exception occurs
  • else: run only when no exception occurred
  • finally: always run, whether or not an exception occurred

Previous
Next