Skip to content

Instantly share code, notes, and snippets.

@yuheiomori
Created September 27, 2014 08:40
Show Gist options
  • Save yuheiomori/bccfe189c39d7c8932ed to your computer and use it in GitHub Desktop.
Save yuheiomori/bccfe189c39d7c8932ed to your computer and use it in GitHub Desktop.
Catch multiple exceptions in one line
# coding=utf-8
class SampleException1(Exception):
message = "sample 1 exception"
class SampleException2(Exception):
message = "sample 2 exception"
def some_process(n):
if n % 2 != 0:
raise SampleException1()
else:
raise SampleException2()
def main():
# 例外の基底クラスをexcept
try:
some_process(1)
except Exception as e:
assert isinstance(e, SampleException1)
try:
some_process(2)
except Exception as e:
assert isinstance(e, SampleException2)
# 例外のタプルをexcept
try:
some_process(1)
except (SampleException1, SampleException2) as e:
assert isinstance(e, SampleException1)
try:
some_process(2)
except (SampleException1, SampleException2) as e:
assert isinstance(e, SampleException2)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment