Question

We have inner try excepts like

try:

    try: (problem here)

    except: (goes here)

except: (will it go here) ??

Is that the currect flow of try excepts ? If an exception is caught inside for the outside try block , its an error or non - error ?

Was it helpful?

Solution

No, it will not go in the second except, unless the first one raises an exception, too.

When you go in the except clause, you are pretty much saying "the exception is caught, I'll handle it", unless you re-raise the exception. For example, this construct can often be quite useful:

try:
    some_code()
    try:
        some_more_code()
    except Exception as exc:
        fix_some_stuff()
        raise exc
except Exception as exc:
    fix_more_stuff()

This allows you to have many layers of "fixing" for the same exception.

OTHER TIPS

It will not reach the outside except, unless you raise another exception within that one, like this:

try:
    try:
        [][1]
    except IndexError:
        raise AttributeError
except AttributeError:
    print("Success! Ish")

Unless the inner except block raises an exception fitting for the outer block, it will not count as an error.

The error will not hit the outer Except. You can test it like such:

x = 'my test'
try:
    try: x = int(x)
    except ValueError: print 'hit error in inner block'
except: print 'hit error in outer block'

This will only print 'hit error in inner block'.

However, say you some other code after the inner Try/Except block, and this raises an error:

x, y = 'my test', 0
try:
    try: x = int(x)
    except ValueError: print 'x is not int'
    z = 10./y
except ZeroDivisionError: print 'cannot divide by zero'

This would print both 'x is not int' AND 'cannot divide by zero'.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top