1

I have two files:

Content in fl_fn1.py:

import fl_fn2

def fn1():
    print("hi")
    try:
        fl_fn2.fn2()
    except:
        print("inside except")
    finally:
        print("finally")

fn1()

Content in fl_fn2.py:

import sys

def fn2():
    print("fn2")
    sys.exit(0)

Now when I invoke fl_fn1.py from Windows command prompt like;

C:\Program Files\Anaconda3\python.exe C:\Users\User1\Desktop\fl_fn1.py

then my output is:

hi
fn2
inside except
finally



However when I change the exception part in fl_fn1.py to:

except Exception as ex:
    print("inside except")

Then my output is:

hi
fn2
finally

The exception part is not executed!!!

Could someone please explain what is going on. I am new to Python.
Thanks in Advance :)

MagnumCodus
  • 171
  • 1
  • 11

2 Answers2

2

SystemExit inherits from BaseException not from Exception so to catch it you need except BaseException as e:. This is deliberate to prevent accidental capture of the exception via except Exception as e:

Chris_Rands
  • 38,994
  • 14
  • 83
  • 119
  • 1
    Oh great thanks @Chris . I was also interested to know the different classes of exceptions, but I googled and got it!!! https://docs.python.org/3/library/exceptions.html#exception-hierarchy – MagnumCodus Feb 13 '20 at 11:03
1

There some logging that will help you to understand your exception type:

import sys

def fn1():
    print("hi")
    try:
        fn2()
    except:
        print("Exception type: ",sys.exc_info()[0], " occured.")
        print("Exception inherits from: ", sys.exc_info()[0].__bases__)
        print("inside except")
    finally:
        print("finally")

fn1()

As @Chris_Rands mentioned in his response, you receive SystemExit exeption which inherits BaseException.

andnik
  • 2,405
  • 2
  • 22
  • 33