Python exception handling a little more convenient

For example, I want to send a specific exception as a different exception class in my library

Can I use it in a scene where I have defined exceptions for the library and it's a hassle to wrap built-in exceptions?

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]

The first is MyException and the second is TypeError.

func(3)  # MyException
func('hoge')  # TypeError

Catch the exception and change the return value

Fine control is impossible.

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

Recommended Posts

Python exception handling a little more convenient
Python exception handling
Python exception handling
Python, about exception handling
Python exception handling (Python learning memo ⑥)
A little more about FIFO
Exception handling during Python API communication
A little more about references ~ Using Python and Java as examples ~
Exception handling
I tried to summarize Python exception handling
Pharmaceutical company researchers summarized Python exception handling
Module import and exception handling in python
Python Error Handling
A story stuck with handling Python binary data
boto3 exception handling
Python timezone handling
python: 3.8-Handling Exception: you need a C compiler to build uWSGI error with alpine
Python Ver. To introduce WebPay with a little code.
[Python for Hikari-] Chapter 07-01 Exception Handling (Errors and Exceptions)
Read a little more arch / arm / boot / compressed / Makefile
A note on handling variables in Python recursive functions
[Python] A convenient library that converts kanji to hiragana
A little bit from Python using the Jenkins API
[python] [Gracenote Web API] A little customization of pygn
(For myself) Flask_2 (list and for, extends, and a little more)
A * algorithm (Python edition)
[Python] Take a screenshot
Handling yaml with python
Create a Python module
Convenient Python methods, etc.
Exception message in Python
Daemonize a Python process
Python decimal point handling
Hexadecimal handling in Python 3
Create a Python environment
Python3> round (a --b, 7)
Python exception class list
Fizzbuzz with exception handling
I just changed the sample source of Python a little.
Take a look at the Python built-in exception tree structure