Created
December 1, 2012 11:04
-
-
Save aflc/4181532 to your computer and use it in GitHub Desktop.
Pythonの例外処理を少し便利に ref: http://qiita.com/items/c39b462376a48eae3646
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
import functools | |
class MyException(Exception): | |
def __init__(self, original, *args, **kwargs): | |
super(MyException, self).__init__(str(original), *args, **kwargs) | |
self.original = original | |
def raise_as(except_classes, target_class): | |
def wrapper(f): | |
@functools.wraps(f) | |
def wrapper_inner(*args, **kwargs): | |
try: | |
return f(*args, **kwargs) | |
except except_classes as e: | |
raise target_class(e) | |
return wrapper_inner | |
return wrapper | |
@raise_as(IndexError, MyException) | |
def func(a): | |
l = [1,2] | |
return l[a] |
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
func(3) # MyException | |
func('hoge') # TypeError |
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
def try_return(except_classes, value=None): | |
def wrapper(f): | |
def wrapper_inner(*args, **kwargs): | |
try: | |
return f(*args, **kwargs) | |
except except_classes: | |
return value | |
return wrapper_inner | |
return wrapper | |
@try_return(ZeroDivisionError, None) | |
def func(x): | |
return 1 / x | |
print func(1) # 1 | |
print func(0) # None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment