Ryflex
Ryflex

Reputation: 5769

Most reliable way of exiting out of a function on a failed try

What is the best way to except out of ALL potential errors?

## Try to...
try:
    ## Print
    print "hi"
## On failure to get data
except Exception:
    ## Exit out of current function
    return

or

## Try to...
try:
    ## Print
    print "hi"
## On failure to get data
except:
    ## Exit out of current function
    return

or are there better ways?

Thanks in advance - Hyflex

Upvotes: 1

Views: 69

Answers (2)

Generally, always catch specific errors you know will occur. Especially if you catch everything, (That is, except:) you will catch KeyboardInterrupt and make your program not be stoppable by Ctrl+C; SystemExit that is used to kill a thread, and so forth... While catching Exception is slightly better, it will still lose too much context; the exceptional condition that occurs might be other than you expected. Thus always catch IOError, ValueError, TypeError and so forth, by their names.

Update

There is 1 case where you want to use except Exception; at a top level of a program, or an action where you want to make sure that the whole program does not crash due to an uncaught Exception.

Upvotes: 3

Amber
Amber

Reputation: 526593

Never use a bare except:. If you do, you'll wind up catching things like SystemExit and KeyboardInterrupt, which are not intended to be caught in most code.

Ideally, you should try to be as specific as possible - for example, catching IOError for a failing print. If you can't predict exactly what exceptions you're concerned about, then at the very least you should use except Exception to avoid the aforementioned problem.

Upvotes: 3

Related Questions