「Python」try except文例外のサンプル

環境
PyCharm 2021.3.3
Python 3.9.2
書式

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
try:
処理コード
except 例外クラス名 [as 変数名]:
処理コード
else:
処理コード
try: 処理コード except 例外クラス名 [as 変数名]: 処理コード else: 処理コード
try:
   処理コード
except 例外クラス名 [as 変数名]:
   処理コード
else:
  処理コード

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# coding: utf-8
try:
a = 120/0
except Exception:
print("数値を0で割るのでエラーです")
else:
print("終了")
# coding: utf-8 try: a = 120/0 except Exception: print("数値を0で割るのでエラーです") else: print("終了")
# coding: utf-8

try:
      a = 120/0
except Exception:
      print("数値を0で割るのでエラーです")
else:
      print("終了")

実行結果
数値を0で割るのでエラーです

Python

Posted by arkgame