キーワードを除くPython
例
ステートメントでエラーが発生した場合は、「問題が発生しました」と出力します。
try:
x > 3
except:
print("Something went wrong")
定義と使用法
キーワードは、except
ブロックを除いてtry ...で使用されます。tryブロックでエラーが発生した場合に実行するコードのブロックを定義します。
エラータイプごとに異なるブロックを定義し、問題が発生しなかった場合に実行するブロックを定義できます。以下の例を参照してください。
その他の例
例
NameErrorの場合は1つのメッセージを書き込み、TypeErrorの場合は別のメッセージを書き込みます。
x = "hello"
try:
x > 3
except NameError:
print("You have a variable that is not defined.")
except TypeError:
print("You are comparing values of different type")
例
エラーを発生させるステートメントを実行しようとしますが、定義されたエラータイプ(この場合はZeroDivisionError)はありません。
try:
x = 1/0
except NameError:
print("You have a
variable that is not defined.")
except TypeError:
print("You
are comparing values of different type")
except:
print("Something else went wrong")
例
エラーが発生しなかった場合は、メッセージを記述します。
x = 1
try:
x > 10
except NameError:
print("You have a variable that is not defined.")
except TypeError:
print("You are comparing values of different type")
else:
print("The 'Try' code was executed without raising any errors!")
関連ページ
try
キーワード。
finally
キーワード。