Checked exceptions are not a thing in Python. But Python does have some similarities in the exception class hierarchy. Here is the Java structure:
source
In Java you have to declare in the method signature if the method will throw an Exception
or any class that inherits from Exception
, but not the RuntimeException
. This rule is called checked exceptions.. it forces the user to consider them or the application will not compile.
In Python we still have a similar concept, but no enforcement. You may have heard before that it's bad style to do a bare except statement, and at the very least you should choose to catch Exception
try:
foo()
except: # bad!
bar()
try:
foo()
except Exception: # somewhat better!
bar()
This is because in Python Exception
extends from BaseException
and a bare except
will catch everything. For example, you probably don't want to catch ctrl+c
which raises a KeyboardInterrupt
. If you do a bare except:
, then KeyboardInterrupt
will be caught, but if you do a except Exception:
you will let this bubble up and stop the application. That is because KeyboardInterrupt
extends BaseException
and not Exception
and therefore wont be caught!