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
, KeyboardInterrupt
및 GeneratorExit
:
>>> 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:
단지 당신이하고 있다는 예외 허용 을 의미 캐치에 있습니다.
Here's an example of one that you're not meant to catch:
>>> try:
... input()
... except:
... pass
...
>>> try:
... input()
... except Exception as e:
... pass
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
KeyboardInterrupt
The first one silenced the KeyboardInterrupt
!
Here's a quick list:
issubclass(BaseException, BaseException)
#>>> True
issubclass(BaseException, Exception)
#>>> False
issubclass(KeyboardInterrupt, BaseException)
#>>> True
issubclass(KeyboardInterrupt, Exception)
#>>> False
issubclass(SystemExit, BaseException)
#>>> True
issubclass(SystemExit, Exception)
#>>> False
If you want to catch any of those, it's best to do
except BaseException:
to point out that you know what you're doing.
All exceptions stem from BaseException
, and those you're meant to catch day-to-day (those that'll be thrown for the programmer) inherit too from Exception
.
There are differences with some exceptions, e.g. KeyboardInterrupt.
Reading PEP8:
A bare except: clause will catch SystemExit and KeyboardInterrupt exceptions, making it harder to interrupt a program with Control-C, and can disguise other problems. If you want to catch all exceptions that signal program errors, use except Exception: (bare except is equivalent to except BaseException:).
Using the second form gives you a variable (named based upon the as
clause, in your example e
) in the except
block scope with the exception object bound to it so you can use the infomration in the exception (type, message, stack trace, etc) to handle the exception in a more specially tailored manor.
'program story' 카테고리의 다른 글
Spring MVC 또는 Spring Boot (0) | 2020.08.04 |
---|---|
Ctrl-C로 Python 스크립트를 죽일 수 없습니다 (0) | 2020.08.04 |
거친 입자 대 미세 입자 (0) | 2020.08.04 |
Golang에서 정수를 부동 수로 변환 (0) | 2020.08.04 |
C ++ 템플릿 생성자 (0) | 2020.08.04 |