Python Script Try Blocks / Error Handling

Is there a way to use try / except / finally blocks in Python Script? Is there documentation somewhere on error handling?

So I somewhat figured this out. I was doing a try statement without the exception statement. It appears you have to have both like this.

try:
    a = 1 / 0
except:
    print "divide by zero error"

What if you want to do the try without raising the exception? The only way I have figured out how to do this is in your exception put in β€œβ€ like this:

try:
    a = 1 / 0
except:
    ""

I think it’s cleaner not to have the exception at all. Is there anyway to do this without the exception?

Fully answered here. Must have the except statement. Instead of using β€œβ€ you can use pass which is equivalent to a blank line of code.

try:
    a = 1 / 0
except:
    pass

Hi @Mike24,

Python contains build in exceptions you can handle individually. However, i would avoid passing on zero division errors without notice. Instead try to check for zero’s before doing a division. Below shows one situation where this could get confusing, the code exits with the zero division error and the second exception for b = x is never reached:

try:
    a = 1 / 0
    b = x
except ZeroDivisionError:
    # print "You attempted to divide by zero"
    pass
except Exception as ex:
    print "Error: {}".format(ex)

_
c.

1 Like

Yes it is always a good Idea to try to catch the most specific exception you can, both to help yourself to understand the code when you come back to it later and to avoid hiding unexpected errors.

1 Like