try-except 구조를 사용하여 Python에서 사용자 정의 예외를 사용하는 방법을 이해하려고합니다.Python의 사용자 정의 예외
# create custom error class
class CustomError1(Exception):
pass
내가 그렇게처럼 사용하려고 : 여기
사용자 정의 예외의 간단한 예입니다 이# using try-except
def fnFoo1(tuple1, tuple2):
try:
assert(len(tuple1) == len(tuple2))
except AssertionError:
raise(CustomError1)
return(1)
fnFoo1((1,2), (1, 2, 3))
이것은 CustomeError1
제기뿐만 아니라 내가하고 싶은 AssertionError
를 제기 CustomError1
에 포함될 것입니다.
다음은 내가 원하는 것을, 그러나 예외가 처리해야하는 방식이 될 것 같지 않습니다.
# use the custom error function without try-catch
def fnFoo2(tuple1, tuple2):
if len(tuple1) != len(tuple2): raise(CustomError1)
print('All done!')
fnFoo2((1,2), (1, 2, 3))
다른 예외를 숨기는 사용자 지정 예외를 작성하는 방법은 무엇입니까?
다음을 보시기 바랍니다 : ankurankan.github.io/blog/2014/06/03/custom-assert-method-in-python/ –
어떤 버전의 Python 3을 사용하고 있습니까? 나중의 3.x 버전에서 예외 동작에 몇 가지 변경 사항이 있음을 기억합니다. – BrenBarn
@brenbarn python 3.3.1 – tchakravarty