[python] Python에서 except :와 예외 e :를 제외하는 것의 차이점

다음 코드 스 니펫은 모두 동일한 작업을 수행합니다. 그들은 모든 예외를 포착하고 except:블록 에서 코드를 실행합니다.

스 니펫 1-

try:
    #some code that may throw an exception
except:
    #exception handling code

스 니펫 2-

try:
    #some code that may throw an exception
except Exception as e:
    #exception handling code

두 구성의 차이점은 무엇입니까?



답변

두 번째로 예외 객체의 속성에 액세스 할 수 있습니다.

>>> def catch():
...     try:
...         asd()
...     except Exception as e:
...         print e.message, e.args
...
>>> catch()
global name 'asd' is not defined ("global name 'asd' is not defined",)

하지만 잡을 수없는 BaseException또는 시스템 종료 예외 SystemExit, KeyboardInterruptGeneratorExit:

>>> def catch():
...     try:
...         raise BaseException()
...     except Exception as e:
...         print e.message, e.args
...
>>> catch()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in catch
BaseException

다음을 제외한 맨손 :

>>> def catch():
...     try:
...         raise BaseException()
...     except:
...         pass
...
>>> catch()
>>> 

자세한 정보는 문서 의 내장 예외 섹션 학습서 의 오류 및 예외 섹션을 참조하십시오.


답변

except:

모든 예외를 수용 하는 반면

except Exception as e:

단지 당신이하고 있다는 예외 허용 을 의미 캐치에 있습니다.

다음은 잡으려고 의도하지 않은 예입니다.

>>> try:
...     input()
... except:
...     pass
...
>>> try:
...     input()
... except Exception as e:
...     pass
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
KeyboardInterrupt

첫 번째는 침묵했다 KeyboardInterrupt!

빠른 목록은 다음과 같습니다.

issubclass(BaseException, BaseException)
#>>> True
issubclass(BaseException, Exception)
#>>> False


issubclass(KeyboardInterrupt, BaseException)
#>>> True
issubclass(KeyboardInterrupt, Exception)
#>>> False


issubclass(SystemExit, BaseException)
#>>> True
issubclass(SystemExit, Exception)
#>>> False

그 중 하나를 잡으려면 최선을 다하는 것이 가장 좋습니다

except BaseException:

당신이하고있는 일을 알고 있다고 지적합니다.


모든 예외는 유래 BaseException, 그리고 그 당신이 (던져 질 것이다 것과 일상 캐치에 의미있는 위해 프로그래머가)에서 너무 상속 Exception.


답변

KeyboardInterrupt와 같은 몇 가지 예외가 있습니다.

PEP8 읽기 :

bare except : 절은 SystemExit 및 KeyboardInterrupt 예외를 포착하여 Control-C로 프로그램을 인터럽트하기 어렵게 만들고 다른 문제를 위장 할 수 있습니다. 프로그램 오류를 알리는 모든 예외를 포착하려면 Exception :를 제외하고 사용하십시오 (Bare 제외는 BaseException : 제외와 동일 함).


답변

두 번째 형식을 사용하면 예외 개체가 바인딩 된 블록 범위에 변수 ( as예 : 절에 따라 이름이 지정됨 e)가 except생겨 예외 (유형, 메시지, 스택 추적 등)의 정보를 사용할 수 있습니다. 보다 특별하게 조정 된 저택에서 예외를 처리하십시오.


답변

이것을 보는 또 다른 방법. 예외 세부 사항을 확인하십시오.

In [49]: try:
    ...:     open('file.DNE.txt')
    ...: except Exception as  e:
    ...:     print(dir(e))
    ...:
['__cause__', '__class__', '__context__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__suppress_context__', '__traceback__', 'args', 'characters_written', 'errno', 'filename', 'filename2', 'strerror', 'with_traceback']

‘as e’구문을 사용하여 액세스 할 수있는 “사물”이 많이 있습니다.

이 코드는이 인스턴스의 세부 정보 만 보여주기위한 것입니다.


답변