Created
September 27, 2014 08:40
-
-
Save yuheiomori/bccfe189c39d7c8932ed to your computer and use it in GitHub Desktop.
Catch multiple exceptions in one line
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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