Catch exceptions from function calls

When i try to os.mkdir it gives me an error, What if i could try(os.mkdir, ...) to prevent from raising exception and return result or exception?

We can return in (exception, result) format and set exception to None if there were no exceptions.

I think this fits in traceback library.

If this feature already exists please comment

I assume you know about

try:
    os.mkdir(...)
except Execption:
   ...

So why do you think there is a need for a try function as well?

And if you simply prefer that form, you can define it yourself:

def try_(fn, *args, **kw):
    try:
        return (None, fn(*args, **kw))
    except Exception as exc:
        return (exc, None)
3 Likes

You can also use contextlib.suppress: contextlib — Utilities for with-statement contexts — Python 3.14.2 documentation

6 Likes

Yes I know that i can define it myself but it would be great to have in python

there are a lot of functions and methods that raise exceptions or return value, if we want to suppress the exceptions we shouldn’t need a whole context manager.

and if we are going to use this approach we shouldn’t discard the error or result.

How woudl you use the proposed syntax? Would you start by first checking if there’s an error, and if so, doing something, and if not, doing something else? Replace your if/else with a try/except and you have proper error handling, done the easy way.

3 Likes

what if we want to delay or hold the exception in a variable?

try:
    result = fn(*args, **kwargs)
    exception = None
except Exception as e:
    result = None
    exception = e

this is long, isn’t it?

also my goal is reducing indentation

Your proposal doesn’t reduce indentation, though. It eliminates the try…except, but replaces it with the need to extract the result and exception from the return value and then check if there was an exception, which almost certainly requires using an if statement. So you have just as much indentation, and more lines of code…

I suggest you do some research into what makes a successful proposal for a language change (“it would be great to have it in Python” isn’t sufficient :slightly_smiling_face:). The “Changing Python” section of the devguide is a good place to start.

Getting a change into the language is a lot of work. Are you willing to invest the effort needed to make it happen? If so, then I’d start by finding some objective evidence that your change will improve the language.

3 Likes

This is generally bad practice because it causes reference cycles: PEP 3110 – Catching Exceptions in Python 3000 | peps.python.org

So introducing a built in, or standard library function, that encourages this practice is unlikely to pass an enhancement proposal.

1 Like

Is this something you actually do? Post some example code where you would in fact do this; there’s almost certainly a tidier way. Remember, exceptions do NOT have to be caught the moment that you are aware they could happen! The entire point of exception handling is that, if you can’t handle the exception, don’t.

I cannot think of any situations where I want to (a) do something that might fail, (b) carry on whether or not it failed, and then (c) inspect the failure later on. Usually, if (a) and (b) are true, I can handle the exception immediately (eg having empty data instead of what would have been loaded from a file), even if the true “handling” of the failure is later. I don’t think I’ve ever needed to do tests on the exception itself long after the event.

2 Likes

can’t gc cleanup the exception object after it’s not used? does it have to be cleaned inside except block?

since you already know about exceptions, is it fine to use exceptions as signals?


class Signal(Exception):
    pass

def a():
    raise Signal('something happened!')

try:
    a()
except Signal as s:
    print(s)

I might fail this in a code review, depending on the rest of the code. If the API is “return True on Mondays, raise Signal on Tuesdays”, then that’s a problem. If the only way out of the function is an exception, that’s a problem, too.

My point is: whether this is a good pattern depends on the context. There’s not enough info here to make a blanket statement.

1 Like

I’m not a fan of this proposal, but there is a niche use case. It’s the RPC (Remote Procedure Call) at the low level. The remote side must signalize if it is returning a result or an exception and what is the exact value. The decision how to handle it, is made elsewhere.

2 Likes

Are you actually looking for result-based error handling / result types as a replacement for exceptions? That would be a major paradigm shift for the core language. But there are third-party packages that support this, see e.g. Returns

2 Likes