Pythonの例外の詳細な説明

高洛峰
リリース: 2017-03-15 13:57:56
オリジナル
1479 人が閲覧しました

各例外は何らかのクラスのインスタンスです。これらのインスタンスはさまざまな方法で発生させてキャッチできるため、プログラムはエラーをキャッチして処理できます


例外処理

キャッチするには例外がある場合は、try/Except ステートメントを使用できます。

トリガー例外を発生させる

>>> def inputnum():
    x=input('Enter the first number: ')
    y=input('Enter the first number: ')
    try:
        print x/y
    except ZeroDivisionError:
        print "The second number can't be zero"

        
>>> inputnum()
Enter the first number: 10
Enter the first number: 0
The second number can't be zero
ログイン後にコピー

複数の例外タイプ

>>> class Muff:
    muffled=False
    def calc(self,expr):
        try:
            return eval(expr)
        except ZeroDivisionError:
            if self.muffled:
                print 'Division by zero is illegal'
            else:
                raise

            
>>> c=Muff()
>>> c.calc(10/2)

Traceback (most recent call last):
  File "<pyshell#33>", line 1, in <module>
    c.calc(10/2)
  File "<pyshell#31>", line 5, in calc
    return eval(expr)
TypeError: eval() arg 1 must be a string or code object
>>> c.calc(&#39;10/2&#39;)
>>> c.calc(&#39;1/0&#39;)

Traceback (most recent call last):
  File "<pyshell#35>", line 1, in <module>
    c.calc(&#39;1/0&#39;)
  File "<pyshell#31>", line 5, in calc
    return eval(expr)
  File "<string>", line 1, in <module>
ZeroDivisionError: integer pision or modulo by zero
>>> c.muffled=True
>>> c.calc(&#39;1/0&#39;)
Division by zero is illegal
ログイン後にコピー

複数の例外を同時にキャッチ

try:
    x=input(&#39;Enter the first number:&#39;)
    y=input(&#39;Enter the seconed number:&#39;)
    print x/y
except ZeroDivisionError:
    print "The second number can&#39;t be zero!"
except TypeError:
    print "That wasn&#39;t a number,was it?"
ログイン後にコピー

オブジェクトをキャッチ

try:
    x=input(&#39;Enter the first number:&#39;)
    y=input(&#39;Enter the seconed number:&#39;)
    print x/y
except(ZeroDivisionError,TypeError,NameError):
    print &#39;Your numbers were bogus...&#39;
ログイン後にコピー

すべての例外をキャッチ

try:
    x=input(&#39;Enter the first number:&#39;)
    y=input(&#39;Enter the seconed number:&#39;)
    print x/y
except(ZeroDivisionError,TypeError),e:
    print e

    
Enter the first number:1
Enter the seconed number:0
integer pision or modulo by zero
ログイン後にコピー


以上がPythonの例外の詳細な説明の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

関連ラベル:
ソース:php.cn
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
最新の問題
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!