# Python CodeRecipe|exceptの使い方
❮ Home ❮ Python Keywords
# exceptの例1
If the statement raises an error print "Something went wrong":
try: x > 3except: print("Something went wrong")
# exceptの定義及び使い方
except関数は、try ...。除く ブロック。tryブロックでエラーが発生した場合に実行するコードブロックを定義します。 エラー・タイプごとに異なるブロックを定義し、 何も問題がなければ、以下の例を参照してください。
# exceptの例2
Write one message if it is a NameError, and another if it is an
TypeError:
x = "hello"try: x > 3except NameError:
print("You have a variable that is not defined.")except TypeError:
print("You are comparing values of different type")
# exceptの例3
Try to execute a statement that raises an error, but none of the defined
error types (in this
case, a ZeroDivisionError):
try: x = 1/0except 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")
# exceptの例4
Write a message if no errors were raised:
x = 1try: x > 10except 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!")
Related Pages The try keyword. The finally keyword.
❮ Home ❮ Python Keywords