Skip to content

Comment on The Ultimate Guide to Error Handling in Python

Comments

Can someone explain the last bit:

    print(f"Unexpected error: {error}")
        sys.exit(1)

How is that any different than just letting the exception throw all the way out?

Is all this doing is making sure the exit code is 1 instead of some other non-zero value?

I'm not seeing how this is any better than just letting the program hard-crash.

(I am asking in earnest. I'm getting back into Python and wanting to know what's generally preferred)

It gives you control over the output of your program (and as you mention, the exact error code - which probably should be 1 in this instance).

It's often more user friendly to print a short human-readable message (or nothing) than to dump a huge stack trace. YMMV, if this is an internal dev tool then the opposite might be true!

I feel like both of them should crash the application. The only benefit is that you don't see the full stack trace in production, which depending on circumstances you don't want to be shown.

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.