Python의 예외 요약

高洛峰
풀어 주다: 2017-02-21 10:16:55
원래의
1602명이 탐색했습니다.

예외는 프로그램상의 예외 및 위반을 의미합니다. 예외 메커니즘은 프로그램에서 오류가 발생한 후 프로그램의 처리 방법을 나타냅니다. 오류가 발생하면 프로그램의 실행 흐름이 바뀌고 프로그램의 제어권이 예외 처리로 넘어갑니다. 다음 글은 Python의 예외 관련 정보를 주로 요약한 것입니다. 도움이 필요한 친구들이 참고할 수 있습니다.

서문

예외 클래스는 일반적으로 사용되는 예외 클래스로 StandardError, StopIteration, GeneratorExit, Warning 및 기타 예외 클래스를 포함합니다. Python의 예외는 상속 구조를 사용하여 생성됩니다. 기본 클래스 예외는 예외 처리기에서 캡처될 수 있으며, Python의 try...Exception 문을 사용하여 다양한 하위 클래스 예외가 캡처될 수 있으며, 예외 절은 다음과 같이 정의됩니다. 절을 시도하십시오.

Python의 예외 처리

예외 처리의 문 구조

try:
 <statements>  #运行try语句块,并试图捕获异常
except <name1>:
 <statements>  #如果name1异常发现,那么执行该语句块。
except (name2, name3):
 <statements>  #如果元组内的任意异常发生,那么捕获它
except <name4> as <variable>:
 <statements>  #如果name4异常发生,那么进入该语句块,并把异常实例命名为variable
except:
 <statements>  #发生了以上所有列出的异常之外的异常
else:
<statements>   #如果没有异常发生,那么执行该语句块
finally:
 <statement>   #无论是否有异常发生,均会执行该语句块。
로그인 후 복사

설명

  • else와 마지막으로 선택 사항이며, 제외하고 0개 이상이 있을 수 있지만, else가 발생하는 경우에는 제외가 하나 이상 있어야 합니다.

  • 예외를 어떻게 지정하더라도 예외는 항상 인스턴스 개체에 의해 식별되며 대부분의 경우 특정 순간에 활성화됩니다. 일단 프로그램 어딘가의 Except 절에 의해 예외가 포착되면, 다른 raise 문이나 오류에 의해 다시 발생하지 않는 한 해당 예외는 종료됩니다.

raise 문

raise 문은 수동으로 예외를 발생시키는 데 사용됩니다.

  • raise #인스턴스는 raise 문 이전이나 raise 문 안에서 생성될 수 있습니다.

  • raise #Python은 암시적으로 클래스의 인스턴스를 생성합니다

  • raise name(value) #예외 값을 발생시키면서 추가 정보 제공

  • raise # 최신 예외를 다시 발생시킵니다

  • E에서 예외 발생

예를 들어 :

은 추가 정보와 함께 ValueError: raise ValueError(&#39;we can only accept positive values&#39;)

을 발생시킵니다. from을 사용할 때 두 번째 표현식은 __cause__ 속성에 연결된 다른 예외 클래스 또는 인스턴스를 지정합니다. 예외가 발생했습니다. 발생한 예외가 포착되지 않으면 Python은 표준 오류 메시지의 일부로 예외를 인쇄합니다:

예를 들어 다음 코드:

try:
 1/0
except Exception as E:
 raise TypeError(&#39;bad input&#39;) from E
로그인 후 복사

실행 결과는 다음과 같습니다.

Traceback (most recent call last):
 File "hh.py", line 2, in <module>
 1/0
ZeropisionError: pision by zero

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
 File "hh.py", line 4, in <module>
 raise TypeError(&#39;bad input&#39;) from E
TypeError: bad input
로그인 후 복사

assert 문

assert 주로 단위 테스트에서 더 많이 사용되는 단언문을 만드는 데 사용되며 나중에 소개됩니다.

with...as 문

with 문은 코드 블록 정의에 대한 시작 및 종료 작업을 지원할 수 있는 보다 풍부한 객체 기반 프로토콜을 지원합니다.

with 문에 해당하는 환경 관리 프로토콜 요구 사항은 다음과 같습니다.

  • 환경 관리자는 __enter____exit__ 메서드를 가지고 있어야 합니다.

초기화 중에 __enter__ 메서드가 실행됩니다. ass 절이 있으면 __enter__ 함수의 반환 값이 변수에 할당됩니다. as 절, else 는 직접 폐기됩니다.

코드 블록에 중첩된 코드가 실행됩니다.

with 블록에서 예외가 발생하면 __exit__(type,value,traceback) 메서드가 호출됩니다(예외 세부정보 포함). 이는 sys.exc_info가 반환하는 값과 동일합니다. 이 메서드가 false를 반환하면 예외가 다시 발생합니다. 그렇지 않으면 비정상적으로 종료됩니다. 일반적인 상황에서는 with 문 외부로 전달될 수 있도록 예외를 다시 발생시켜야 합니다.

with 코드 블록이 예외를 발생시키지 않으면 __exit__ 메서드는 계속 호출되고 해당 유형, 값 및 역추적 매개변수는 None으로 전달됩니다.

다음은 간단한 사용자 정의 컨텍스트 관리 클래스입니다.

class Block:
 def __enter__(self):
  print(&#39;entering to the block&#39;)
  return self
 
 def prt(self, args):
  print(&#39;this is the block we do %s&#39; % args)

 def __exit__(self,exc_type, exc_value, exc_tb):
  if exc_type is None:
   print(&#39;exit normally without exception&#39;)
  else:
   print(&#39;found exception: %s, and detailed info is %s&#39; % (exc_type, exc_value))
  return False

with Block() as b:
 b.prt(&#39;actual work!&#39;)
 raise ValueError(&#39;wrong&#39;)
로그인 후 복사

위의 raise 문에서 로그아웃하면 정상적으로 종료됩니다.

raise 문을 로그아웃하지 않고 실행한 결과는 다음과 같습니다.

entering to the block
this is the block we do actual work!
found exception: <class &#39;ValueError&#39;>, and detailed info is wrong
Traceback (most recent call last):
 File "hh.py", line 18, in <module>
 raise ValueError(&#39;wrong&#39;)
ValueError: wrong
로그인 후 복사

예외 처리기

예외가 발생하면 sys.exc_info() 함수를 호출하여 3개의 요소를 포함하는 튜플을 반환할 수 있습니다. 첫 번째 요소는 예외를 발생시킨 클래스이고, 두 번째 요소는 실제로 발생한 인스턴스입니다. 세 번째 요소인 추적 개체는 예외가 원래 발생했을 때의 호출 스택을 나타냅니다. 모든 것이 정상이면 3 None이 반환됩니다.

Python의 내장 모듈에 정의된 예외

|Exception Name|Description|
|BaseException|Root class for all exceptions|
| SystemExit|Request termination of Python interpreter|
|KeyboardInterrupt|User interrupted execution (usually by pressing Ctrl+C)|
|Exception|Root class for regular exceptions|
| StopIteration|Iteration has no further values|
| GeneratorExit|Exception sent to generator to tell it to quit|
| SystemExit|Request termination of Python interpreter|
| StandardError|Base class for all standard built-in exceptions|
|  ArithmeticError|Base class for all numeric calculation errors|
|   FloatingPointError|Error in floating point calculation|
|   OverflowError|Calculation exceeded maximum limit for numerical type|
|   ZeropisionError|pision (or modulus) by zero error (all numeric types)|
|  AssertionError|Failure of assert statement|
|  AttributeError|No such object attribute|
|  EOFError|End-of-file marker reached without input from built-in|
|  EnvironmentError|Base class for operating system environment errors|
|   IOError|Failure of input/output operation|
|   OSError|Operating system error|
|    WindowsError|MS Windows system call failure|
|    ImportError|Failure to import module or object|
|    KeyboardInterrupt|User interrupted execution (usually by pressing Ctrl+C)|
|   LookupError|Base class for invalid data lookup errors|
|    IndexError|No such index in sequence|
|    KeyError|No such key in mapping|
|   MemoryError|Out-of-memory error (non-fatal to Python interpreter)|
|   NameError|Undeclared/uninitialized object(non-attribute)|
|    UnboundLocalError|Access of an uninitialized local variable|
|   ReferenceError|Weak reference tried to access a garbage collected object|
|   RuntimeError|Generic default error during execution|
|    NotImplementedError|Unimplemented method|
|   SyntaxError|Error in Python syntax|
|    IndentationError|Improper indentation|
|     TabErrorg|Improper mixture of TABs and spaces|
|   SystemError|Generic interpreter system error|
|   TypeError|Invalid operation for type|
|   ValueError|Invalid argument given|
|    UnicodeError|Unicode-related error|
|     UnicodeDecodeError|Unicode error during decoding|
|     UnicodeEncodeError|Unicode error during encoding|
|     UnicodeTranslate Error|Unicode error during translation|
|  Warning|Root class for all warnings|
|   DeprecationWarning|Warning about deprecated features|
|   FutureWarning|Warning about constructs that will change semantically in the future|
|   OverflowWarning|Old warning for auto-long upgrade|
|   PendingDeprecation Warning|Warning about features that will be deprecated in the future|
|   RuntimeWarning|Warning about dubious runtime behavior|
|   SyntaxWarning|Warning about dubious syntax|
|   UserWarning|Warning generated by user code|
로그인 후 복사

Python의 예외(Exception )에 대해 자세히 알아보세요. 관련 기사를 보려면 PHP 중국어 웹사이트를 주목하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!