「Python」raise 文で例外を出力するサンプル

2020年12月10日

書式
raise 例外クラス名(引数の値)
raise 文を使って、特定の例外を発生させることができます。
使用例1

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# coding: utf-8
#!/usr/bin/python3
try:
kk = 20/3
raise Exception('unexception aaa')
except Exception as e:
print(e)
# coding: utf-8 #!/usr/bin/python3 try: kk = 20/3 raise Exception('unexception aaa') except Exception as e: print(e)
# coding: utf-8

#!/usr/bin/python3

try:
      kk = 20/3
      raise Exception('unexception aaa')

except Exception as e:
      print(e)

実行結果
>python test.py
unexception aaa

使用例2

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# coding: utf-8
#!/usr/bin/python3
try:
cft = 50/5
raise Exception('exception test','error msg')
except Exception as e:
print(e)
# coding: utf-8 #!/usr/bin/python3 try: cft = 50/5 raise Exception('exception test','error msg') except Exception as e: print(e)
# coding: utf-8

#!/usr/bin/python3
try:
      cft = 50/5
      raise Exception('exception test','error msg')

except Exception as e:
      print(e)

実行結果
>python test.py
('exception test’, 'error msg’)

Python

Posted by arkgame