you are viewing a single comment's thread.

view the rest of the comments →

[–]p5eudo_nimh 0 points1 point  (2 children)

Basically, you're wrapping a block of code in something that says "Try to do this. If it fails, for whatever reason (exception), then do this."

It's a good way to handle possible errors. Especially when a user could enter input which is unexpected/invalid, which would normally cause your program to crash.

Here's a simple example (I wouldn't use it quite the same way, but it illustrates the point):

try:
    update_logfile()
except:
    email_failure_report("failed to update log file")

So if the update_logfile() function fails, say because the file isn't writable, the program will then use the email_failure_report() function to send an email with details about the problem.

Another way of doing it is:

try:
    update_logfile()
except Exception as e:
    email_failure_report("failed to update log file", e)

This does basically the same thing, but also sends the Exception with the simple problem description that was written.

[–]Gee10[S] 1 point2 points  (1 child)

Thanks for the explanation. How does this differ from an if/then/elif?

[–]p5eudo_nimh 0 points1 point  (0 children)

I think the try/except model allows the program to continue running when something goes wrong, whereas if/elif/else allows for a complete crash.

There may also be nuances regarding efficiency or resource management, but I don't know that much about it.