한 줄로 여러 예외를 잡으십시오 (블록 제외)
질문
나는 내가 할 수 있다는 것을 알고있다 :
try:
# do something that may fail
except:
# do this if ANYTHING goes wrong
나는 또한 이것을 할 수있다 :
try:
# do something that may fail
except IDontLikeYouException:
# say please
except YouAreTooShortException:
# stand on a ladder
그러나 두 가지 다른 예외에서 똑같은 일을하고 싶다면 지금 내가 생각할 수있는 최선은 이것을하는 것입니다.
try:
# do something that may fail
except IDontLikeYouException:
# say please
except YouAreBeingMeanException:
# say please
이런 식으로 할 수있는 방법이 있습니까 (예외를 두 가지 예외를 알려주는 것입니다) :
try:
# do something that may fail
except IDontLikeYouException, YouAreBeingMeanException:
# say please
이제는 다음과 같은 구문과 일치하므로 실제로 작동하지 않습니다.
try:
# do something that may fail
except Exception, e:
# say please
따라서 두 가지 뚜렷한 예외를 잡으려는 나의 노력은 정확히 오지 않습니다.
이것을 할 수있는 방법이 있습니까?
답변
파이썬 문서에서 :
이외 절은 예를 들어 괄호로 된 튜플로 여러 예외를 지명 할 수 있습니다.
except (IDontLikeYouException, YouAreBeingMeanException) as e:
pass
또는 Python 2에만 해당 :
except (IDontLikeYouException, YouAreBeingMeanException), e:
pass
쉼표로 변수에서 예외를 분리하면 Python 2.6 및 2.7에서는 여전히 작동하지만 이제는 비례가 없어 Python 3에서 작동하지 않습니다.이제 당신은 그대로 사용해야합니다.
답변
한 줄에서 여러 예외를 어떻게 잡는 것이 어떻게됩니까?
이 작업을 수행:
try:
may_raise_specific_errors():
except (SpecificErrorOne, SpecificErrorTwo) as error:
handle(error) # might log or have some other default behavior...
쉼표를 사용하여 쉼표를 사용하여 오류 개체를 이름에 할당하는 구형 구문으로 인해 괄호가 필요합니다.AS 키워드는 할당에 사용됩니다.오류 개체의 이름을 사용할 수 있습니다. i 오류를 개인적으로 선호합니다.
모범 사례
현재 Python과 호환되는 방식 으로이 작업을 수행하려면 예외를 쉼표로 분리하고 괄호를 사용하여 예외 인스턴스를 할당 한 이전 구문과 차별화하여 예외 유형을 다음과 같은 예외 유형에 따라 변수 이름과 차별화 할 수 있습니다.반점.
간단한 사용의 예는 다음과 같습니다.
import sys
try:
mainstuff()
except (KeyboardInterrupt, EOFError): # the parens are necessary
sys.exit(0)
나는 버그를 숨기지 않도록 이러한 예외 만 지정하는 것입니다.이 경우 Full Stack Trace에서 전체 스택 추적을 기대합니다.
여기에 설명되어 있습니다 : https://docs.python.org/tutorial/errors.html.
예외를 변수에 할당 할 수 있습니다 (e는 일반적이지만, 예외 처리가 길어지면 더 큰 자세한 변수를 선호 할 수 있습니다.다음은 예제입니다.
import sys
try:
mainstuff()
except (KeyboardInterrupt, EOFError) as err:
print(err)
print(err.args)
sys.exit(0)
Python 3에서는 오류 객체가 제외 한 블록이 체결 될 때 범위가 떨어지게됩니다.
익숙한
쉼표로 오류를 할당하는 코드가 표시 될 수 있습니다.Python 2.5 및 이전 버전에서 사용할 수있는 유일한 양식은 사용되지 않으며 코드를 Python 3에서 전달할 수있게되면 구문을 업데이트하여 새 양식을 사용해야합니다.
import sys
try:
mainstuff()
except (KeyboardInterrupt, EOFError), err: # don't do this in Python 2.6+
print err
print err.args
sys.exit(0)
CodeBase에서 쉼표 이름 지정을보고 파이썬 2.5 이상을 사용하고 있으면 업그레이드 할 때 코드가 호환되도록 새로운 방법으로 전환하십시오.
억제 컨텍스트 관리자
허용되는 답변은 정말로 4 줄의 코드입니다.
try:
do_something()
except (IDontLikeYouException, YouAreBeingMeanException) as e:
pass
Passon 3.4에서 사용할 수있는 Suppress 컨텍스트 관리자가있는 단일 줄에서는 패스 라인을 처리 할 수 있습니다.
from contextlib import suppress
with suppress(IDontLikeYouException, YouAreBeingMeanException):
do_something()
따라서 특정 예외를 전달하려는 경우 억제를 사용하십시오.
답변
파이썬 문서에서 -> 8.3 취급 예외 :
TRY 문은 하나 이상의 EXCEES 절을 가질 수 있으며 지정하려면 다른 예외를위한 핸들러.대부분의 핸들러에서는됩니다 실행됩니다.핸들러는 해당 예외 만 처리합니다 해당 시도의 다른 핸들러가 아닌 해당 Try 절 성명.이제 조항은 여러 개의 예외를 A로 명명 할 수 있습니다 예를 들어, 괄호가 된 튜플, 예를 들어 : 제외 (RunTimeError, TypeError, NameError) : 통과하다 이 튜플 주변의 괄호는 필요합니다. 왜냐하면 ValueError를 제외하고 E : 정상적으로 무엇이 있는지에 사용 된 구문이었습니다. exideerror를 제외하고는 e : 현대 파이썬에서 (설명 아래에).이전 구문은 거래 호환성을 위해 여전히 지원됩니다. 즉, 런타임 오류를 제외하고 TypeError는 다음과 같지 않습니다. 제외 (RunTimeError, TypeError) : 그러나 runtimeError를 제외한 TypeError : 당신이 원하는 것은 아닙니다.
답변
많은 수의 예외를 자주 사용하는 경우 튜플을 미리 정의 할 수 있으므로 여러 번 다시 입력 할 필요가 없습니다.
#This example code is a technique I use in a library that connects with websites to gather data
ConnectErrs = (URLError, SSLError, SocketTimeoutError, BadStatusLine, ConnectionResetError)
def connect(url, data):
#do connection and return some data
return(received_data)
def some_function(var_a, var_b, ...):
try: o = connect(url, data)
except ConnectErrs as e:
#do the recovery stuff
blah #do normal stuff you would do if no exception occurred
메모:
If you, also, need to catch other exceptions than those in the pre-defined tuple, you will need to define another except block.
If you just cannot tolerate a global variable, define it in main() and pass it around where needed...
답변
이것을하는 방법 중 하나는 ..
try:
You do your operations here;
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception list,
then execute this block.
......................
else:
If there is no exception then execute this block.
또 다른 방법은 블록을 제외하고 작업을 수행하는 메소드를 작성하고 작성한 모든 블록을 통해이를 호출하는 방법을 만드는 것입니다.
try:
You do your operations here;
......................
except Exception1:
functionname(parameterList)
except Exception2:
functionname(parameterList)
except Exception3:
functionname(parameterList)
else:
If there is no exception then execute this block.
def functionname( parameters ):
//your task..
return [expression]
나는 두 번째 사람이 이것을하는 가장 좋은 방법이 아니라는 것을 알고 있지만, 나는이 일을 할 수있는 방법을 보여주는 것입니다.
답변
출처:https://stackoverflow.com/questions/6470428/catch-multiple-exceptions-in-one-line-except-block
최근댓글