検索

Pythonの例外の概要

Oct 20, 2016 am 09:30 AM
python

Python は例外オブジェクトを使用して例外を表します。エラーが発生すると、例外がスローされます。例外オブジェクトが処理されない、またはキャッチされない場合、プログラムはいわゆるトレースバック (エラー メッセージ) で実行を終了します:

>>> 1/0

Traceback (most 最新の呼び出し 最後):

File " "、1 行目、

1/0

ZeroDivisionError: 整数除算またはゼロによるモジュロ

raise ステートメント

例外を発生させるには、クラス (Exception のサブクラス) またはインスタンスを使用して raise を呼び出すことができます。パラメータ番号ステートメント。次の例では、組み込み例外クラスを使用しています:

>>> raise Exception    #引发一个没有任何错误信息的普通异常
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
raise Exception
Exception
>>> raise Exception(&#39;hyperdrive overload&#39;)   # 添加了一些异常错误信息
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
raise Exception(&#39;hyperdrive overload&#39;)
Exception: hyperdrive overload

システムに付属の組み込み例外クラス:

>>> importExceptions

>>> dir(例外)

[' ArithmeticError'、'AssertionError'、'AttributeError'、'BaseException'、'BufferError'、'BytesWarning'、'DeprecationWarning'、'EOFError'、'EnvironmentError'、'Exception'、'FloatingPointError'、'FutureWarning'、'GeneratorExit' , 'IOError '、'ImportError'、'ImportWarning'、'IndentationError'、'IndexError'、'KeyError'、'KeyboardInterrupt'、'LookupError'、'MemoryError'、'NameError'、'NotImplementedError'、'OSError'、' OverflowError'、'PendingDeprecationWarning'、'ReferenceError'、'RuntimeError'、'RuntimeWarning'、'StandardError'、'StopIteration'、'SyntaxError'、'SyntaxWarning'、'SystemError'、'SystemExit'、'TabError'、'TypeError' 、'UnboundLocalError '、'UnicodeDecodeError'、'UnicodeEncodeError'、'UnicodeError'、'UnicodeTranslateError'、'UnicodeWarning'、'UserWarning'、'ValueError'、'Warning'、'WindowsError'、'ZeroDivisionError'、'__doc__'、' __name__'、'__package__']

すごい!一般的に使用される組み込み例外クラスが多数あります。

カスタム例外

組み込み例外クラスはほとんどの状況をカバーしており、多くの要件には十分ですが、独自の例外クラスを作成する必要がある場合もあります。

他の一般的なクラスと同様に、直接的または間接的に Exception クラスから継承するようにしてください。次のようになります:

>>> class someCustomExcetion(Exception):pass

もちろん、このクラスにいくつかのメソッドを追加することもできます。

例外のキャッチ

try/excel を使用して例外のキャッチと処理を実装できます。

ユーザーが 2 つの数値を入力してそれらを除算できるプログラムを作成するとします。 #どうですか?今回はさらにフレンドリーです

ユーザーとの対話中に例外情報をユーザーに見せたくない場合は、デバッグ中に例外を発生させた方がよいでしょう。 「ブロック」メカニズムをオン/オフにするにはどうすればよいですか?

x = input(&#39;Enter the first number: &#39;)
y = input(&#39;Enter the second number: &#39;)
print x/y
#运行并且输入
Enter the first number: 10
Enter the second number: 0
Traceback (most recent call last):
File "I:/Python27/yichang", line 3, in <module>
print x/y
ZeroDivisionError: integer division or modulo by zero
为了捕捉异常并做出一些错误处理,可以这样写:
try:
x = input(&#39;Enter the first number: &#39;)
y = input(&#39;Enter the second number: &#39;)
print x/y
except ZeroDivisionError:
  print "输入的数字不能为0!"
  
#再来运行
>>>
Enter the first number: 10
Enter the second number: 0

複数のexcel句

上記のプログラムを実行し(2つの数値を入力して割り算を計算する)、上記の内容を入力すると、別の例外が生成されます:

class MuffledCalulator:
muffled = False   #这里默认关闭屏蔽
def calc(self,expr):
try:
return eval(expr)
except ZeroDivisionError:
if self.muffled:
print &#39;Divsion by zero is illagal&#39;
else:
raise
#运行程序:
>>> calculator = MuffledCalulator()
>>> calculator.calc(&#39;10/2&#39;)
5
>>> calculator.clac(&#39;10/0&#39;)
Traceback (most recent call last):
File "<pyshell#30>", line 1, in <module>
calculator.clac(&#39;10/0&#39;)
AttributeError: MuffledCalulator instance has no attribute &#39;clac&#39;   #异常信息被输出了
>>> calculator.muffled = True   #现在打开屏蔽
>>> calculator.calc(&#39;10/0&#39;)
Divsion by zero is illagal


OK!この状況を処理する例外ハンドラーを追加できます:

try:
x = input(&#39;Enter the first number: &#39;)
y = input(&#39;Enter the second number: &#39;)
print x/y
except ZeroDivisionError:
  print "输入的数字不能为0!"
  
#运行输入:
>>>
Enter the first number: 10
Enter the second number: &#39;hello.word&#39;  #输入非数字
Traceback (most recent call last):
File "I:\Python27\yichang", line 4, in <module>
print x/y
TypeError: unsupported operand type(s) for /: &#39;int&#39; and &#39;str&#39;  #又报出了别的异常信息

数字を入力してください!

1 つのブロックで複数の例外をキャッチ

もちろん、1 つのブロックを使用して複数の例外をキャッチすることもできます:

try:
x = input(&#39;Enter the first number: &#39;)
y = input(&#39;Enter the second number: &#39;)
print x/y
except ZeroDivisionError:
print "输入的数字不能为0!"
except TypeError:           # 对字符的异常处理
  print "请输入数字!"
  
#再来运行:
>>>
Enter the first number: 10
Enter the second number: &#39;hello,word&#39;

"

すべての例外をキャッチ

上記 プログラムを実行した後、次の内容を入力すると

どうすればいいでしょうか? 本当にすべての例外をキャッチするためにコードを使用したい場合は、誤って無視してしまうことがあります。 , その後、Except 句内のすべての例外クラスを無視できます:

try:
x = input(&#39;Enter the first number: &#39;)
y = input(&#39;Enter the second number: &#39;)
print x/y
except (ZeroDivisionError,TypeError,NameError):
print "你的数字不对!

エラーが発生しました!

End

心配しないでください。ユーザーが誤って間違ったものを入力しました。情報、もう一度参加するチャンスを与えてもらえますか? 負けたときに確実に終了するようにループを追加できます:

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
Pythonのハイブリッドアプローチ:コンピレーションと解釈を組み合わせたPythonのハイブリッドアプローチ:コンピレーションと解釈を組み合わせたMay 08, 2025 am 12:16 AM

pythonusesahybridapproach、コンコイリティレーショントビテコードと解釈を組み合わせて、コードコンピレッドフォームと非依存性bytecode.2)

Pythonの「for」と「while」ループの違いを学びますPythonの「for」と「while」ループの違いを学びますMay 08, 2025 am 12:11 AM

keydifferencesは、「for」と「while "loopsare:1)" for "for" loopsareideal forterating overencesonownowiterations、while2) "for" for "for" for "for" for "for" for "for" for for for for "wide" loopsarebetterunuinguntinunuinguntinisisisisisisisisisisisisisisisisisisisisisisisisisisisations.un

重複したPython Concatenateリスト重複したPython ConcatenateリストMay 08, 2025 am 12:09 AM

Pythonでは、さまざまな方法でリストを接続して重複要素を管理できます。1)オペレーターを使用するか、すべての重複要素を保持します。 2)セットに変換してから、リストに戻ってすべての重複要素を削除しますが、元の順序は失われます。 3)ループを使用するか、包含をリストしてセットを組み合わせて重複要素を削除し、元の順序を維持します。

Pythonリスト連結パフォーマンス:速度比較Pythonリスト連結パフォーマンス:速度比較May 08, 2025 am 12:09 AM

fasteStMethodDodforListConcatenationinpythOndontsonistize:1)forsmallLists、operatorisefficient.2)forlargerlists、list.extend()orlistcomlethingisfaster、withextend()beingmorememory-efficient bymodifyigniviselistinistin-place。

Pythonリストに要素をどのように挿入しますか?Pythonリストに要素をどのように挿入しますか?May 08, 2025 am 12:07 AM

to insertelementsIntopeaseThonList、useappend()toaddtotheend、insert()foraspificposition、andextend()formultipleElements.1)useappend()foraddingsingleitemstotheend.2)useintert()toaddataspecificindex、cont'slowerforforgelists.3)

Pythonリストは、フードの下に動的な配列またはリンクリストですか?Pythonリストは、フードの下に動的な配列またはリンクリストですか?May 07, 2025 am 12:16 AM

PythonListsareimplementedasdynamicarrays、notlinkedlists.1)they restorediguourmemoryblocks、それはパフォーマンスに影響を与えることに影響を与えます

Pythonリストから要素をどのように削除しますか?Pythonリストから要素をどのように削除しますか?May 07, 2025 am 12:15 AM

pythonoffersfourmainmethodstoremoveelements fromalist:1)removesthefirstoccurrenceofavalue、2)pop(index(index(index)removes regvess returnsaspecifiedindex、3)delstatementremoveselementselementsbyindexorseLice、および4)clear()

スクリプトを実行しようとするときに「許可を拒否された」エラーを取得した場合、何を確認する必要がありますか?スクリプトを実行しようとするときに「許可を拒否された」エラーを取得した場合、何を確認する必要がありますか?May 07, 2025 am 12:12 AM

toresolvea "許可denided" errors whenrunningascript、sofflowthesesteps:1)checkandadaddadaddadadaddaddadadadaddadaddadaddadaddaddaddaddaddadaddadaddaddaddaddadaddaddaddadadaddadaddadaddadadisionsisingmod xmyscript.shtomakeitexexutable.2)

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

AtomエディタMac版ダウンロード

AtomエディタMac版ダウンロード

最も人気のあるオープンソースエディター

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

SublimeText3 Linux 新バージョン

SublimeText3 Linux 新バージョン

SublimeText3 Linux 最新バージョン

VSCode Windows 64 ビットのダウンロード

VSCode Windows 64 ビットのダウンロード

Microsoft によって発売された無料で強力な IDE エディター