>  기사  >  백엔드 개발  >  Python의 예외에 대한 자세한 설명

Python의 예외에 대한 자세한 설명

高洛峰
高洛峰원래의
2017-03-15 13:57:561473검색

각 예외는 일부 클래스의 인스턴스입니다. 이러한 인스턴스는 다양한 방법으로 발생하고 포착될 수 있으므로 프로그램이 오류를 포착하고 처리할 수 있습니다.


>>> 1/0

Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    1/0
ZeropisionError: integer pision or modulo by zero


예외 처리

예외를 포착하려면 try/Exception 문을 사용할 수 있습니다.

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

        
>>> inputnum()
Enter the first number: 10
Enter the first number: 0
The second number can&#39;t be zero


트리거 예외 발생

>>> class Muff:
    muffled=False
    def calc(self,expr):
        try:
            return eval(expr)
        except ZeroDivisionError:
            if self.muffled:
                print &#39;Division by zero is illegal&#39;
            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?"

동시에 여러 개 잡기 time Exception

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;

catchobject

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


모든 예외 catch

try:
    x=input(&#39;Enter the first number:&#39;)
    y=input(&#39;Enter the seconed number:&#39;)
    print x/y
except:
    print &#39;something wrong happened...&#39;

    
Enter the first number:
something wrong happened...


위 내용은 Python의 예외에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.