Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it reasonable to declare an exception type for a single function?

Say I have this code:

def wait_for_x(timeout_at=None):
    while condition_that_could_raise_exceptions
        if timeout_at is not None and time.time() > timeout_at:
            raise SOMEEXCEPTIONHERE

        do_some_stuff()

try:
    foo()
    wait_for_x(timeout_at=time.time() + 10)
    bar()
except SOMEEXCEPTIONHERE:
    # report timeout, move on to something else

How do I pick an exception type SOMEEXCEPTIONHERE for the function? Is it reasonable to create a unique exception type for that function, so that there's no danger of condition_that_could_raise_exceptions raising the same exception type?

wait_for_x.Timeout = type('Timeout', (Exception,), {})
like image 914
Eric Avatar asked Nov 03 '22 21:11

Eric


1 Answers

If distinguishing exceptions from wait_for_x from those from condition_that_could_raise_exceptions is important enough, then sure, define a new exception type. After all, the type is the main way of distinguishing different kinds of exceptions, and parsing the message tends to get messy pretty quickly.

like image 145
Fred Foo Avatar answered Nov 11 '22 06:11

Fred Foo