>  기사  >  백엔드 개발  >  Python 예외 요약

Python 예외 요약

高洛峰
高洛峰원래의
2016-10-20 09:30:261341검색

Python은 예외 객체를 사용하여 비정상적인 상황을 나타냅니다. 오류가 발생하면 예외가 발생합니다. 예외 객체가 처리되거나 포착되지 않으면 프로그램은 소위 트레이스백(오류 메시지)을 사용하여 실행을 종료합니다.

>>> 1/0

트레이스백( 가장 최근 호출 마지막):

파일 "", 라인 1,

1/0

ZeroDivisionError: 정수 나누기 또는 0으로 모듈로

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

시스템과 함께 제공되는 내장 예외 클래스:

>>> 예외 가져오기

>>> 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/Exception을 사용하여 예외 포착 및 처리를 구현할 수 있습니다.

사용자가 두 개의 숫자를 입력한 후 나누는 프로그램을 만든다고 가정해 보겠습니다.

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

입력한 숫자는 다음과 같습니다. 0! #어때요? 이번에는 훨씬 더 친숙해졌습니다

사용자와 상호 작용하는 동안 사용자가 예외 정보를 볼 수 없도록 하려면 디버깅 중에 예외를 발생시키는 것이 좋습니다. "차단" 메커니즘을 어떻게 켜고/끄나요?

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


여러 절 제외

위를 실행하면(숫자 2개 입력 , 찾기 Division) 프로그램에 표면의 내용을 입력하면 또 다른 예외가 발생합니다:

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;  #又报出了别的异常信息

좋아요! 이 상황을 처리하기 위해 예외 처리기를 추가할 수 있습니다.

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;

숫자를 입력하세요!

한 블록으로 여러 예외 포착

물론 한 블록을 사용하여 여러 예외를 포착할 수도 있습니다.

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 "你的数字不对!

"

모든 예외 잡기

위 프로그램처럼 프로그램이 여러 예외를 처리하더라도 실행 후 아래와 같은 내용을 입력하면

>>>
Enter the first number: 10
Enter the second number:   #不输入任何内容,回车
Traceback (most recent call last):
File "I:\Python27\yichang", line 3, in <module>
y = input(&#39;Enter the second number: &#39;)
File "<string>", line 0
^
SyntaxError: unexpected EOF while parsing

실수로 무시하는 상황이 항상 있습니다. 모든 예외를 포착하기 위해 코드를 사용하려면 Ignore를 제외하고 사용할 수 있습니다. 절의 모든 예외 클래스:

try:
x = input(&#39;Enter the first number: &#39;)
y = input(&#39;Enter the second number: &#39;)
print x/y
except:
print &#39;有错误发生了!&#39;
#再来输入一些内容看看
>>>
Enter the first number: &#39;hello&#39; * )0

오류가 발생했습니다.

걱정하지 마세요! 마지막 상황에 대해 이야기해 보겠습니다. 사용자가 실수로 잘못된 정보를 입력했습니다. 다시 입력할 수 있는 기회를 줄 수 있나요? 패배 시 종료되도록 루프를 추가할 수 있습니다.

while True:
try:
x = input(&#39;Enter the first number: &#39;)
y = input(&#39;Enter the second number: &#39;)
value = x/y
print &#39;x/y is&#39;,value
except:
print &#39;列效输入,再来一次!&#39;
#运行
>>>
Enter the first number: 10
Enter the second number:
列效输入,再来一次!
Enter the first number: 10
Enter the second number: &#39;hello&#39;
列效输入,再来一次!
Enter the first number: 10
Enter the second number: 2
x/y is 5



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