カランPythonの基本チュートリアル - 第7章:Python関数(c)のエラー処理メカニズム

I CSDNブログコラム:HTTPS://blog.csdn.net/yty_7
Githubの住所ます。https://github.com/yot777/Python-Primary-Learning

 

7.5 プログラムエラー処理機構

Pythonのプログラムが実行されているエラーが発生した場合、プログラムは実行を中断し、エラーがスローされます。プログラマは自分のミスや取引のキャプチャをプログラムしたい場合は、使用することができます試して...除いて...最後に... エラー処理メカニズム。

 

トライエラーを実行した場合、次のコードは進まないだろう、コードを実行するが、エラー処理コードへのジャンプ、すなわち除いてブロック。

終了実行以外があれば後は、最終的には、ステートメントブロックが実行されて最終的に文のブロックは、これまでのところ、終了します。

あなたがミスをしない場合、我々は実行する必要があります最終的には文ブロックを注:最終的に文はできません

 

Pythonの使用試し1:

try:
  print('try...')
  s=int(input('Please input number:'))
  print('Result:',10/s)
except ValueError as e1:
  print('ValueError Exception:', e1)
except ZeroDivisionError as e2:
  print('ZeroDivisionError Exception:', e2)
finally:
  print('END')

运行结果:
try...
Please input number:5
Result: 2.0
END

try...
Please input number:0
ZeroDivisionError Exception: division by zero
END

try...
Please input number:a
ValueError Exception: invalid literal for int() with base 10: 'a'
END

PythonのすべてのエラーからあるBaseExceptionの派生クラス。あなたは名前が間違って投げかわからない場合は、直接使用する電子などの例外を除いてその上に。

エラーが発生しなかった場合はさらに、あなたがすることができますを除いて、後のステートメントブロックの追加、他のエラーが発生していない時に、自動的に実行し、他のステートメントを。プログラムが発生したエラーを持っている場合しかし、else文は実行されません。

 

Pythonの使用試し2:

try:
  print('try...')
  s=int(input('Please input number:'))
  print('Result:',10/s)
except Exception as e:
  print('Exception is:', e)
else:
  print('No error!')
finally:
  print('END')

运行结果:
try...
Please input number:5
Result: 2.0
No error!
END


try...
Please input number:0
Exception is: division by zero
END

try...
Please input number:a
Exception is: invalid literal for int() with base 10: 'a'
END

Pythonはまた、使用することができレイズステートメントカスタムエラーを。

 

Pythonは使用して昇給を

def func1():
  s=int(input('Please input number:'))
  if s==0:
    raise Exception('除数不能为0!')
  print('Result:',10/s)
try:
  func1()
except Exception as err:
  print('错误信息是:',err)
else:
  print('No error!')

运行结果:
Please input number:2
Result: 5.0
No error!

Please input number:0
错误信息是: 除数不能为0!

Please input number:3.4
错误信息是: invalid literal for int() with base 10: '3.4'

Please input number:a
错误信息是: invalid literal for int() with base 10: 'a‘

(如果raise没有自定义的错误,Exception将返回Python定义的错误)

リファレンスチュートリアル:

Pythonのチュートリアルの遼雪峰

https://www.liaoxuefeng.com/wiki/1016959663602400

遼雪峰のJavaチュートリアル

https://www.liaoxuefeng.com/wiki/1252599548343744

python3チュートリアル|チュートリアル新人
https://www.runoob.com/python3/
 

あなたはBenpianの章では、歓迎の注意をあなたを助けていると感じた場合は、コメント、親指アップ!Githubのは、あなたが、スターをフォロー歓迎します!
 

发布了25 篇原创文章 · 获赞 3 · 访问量 2159

おすすめ

転載: blog.csdn.net/yty_7/article/details/104187671