Do we have a concept of checked and unchecked exceptions in Python?

Viewed 1797

One of my friends who works on JAVA asked me how do I handle checked and unchecked exceptions in Python. I haven't heard these terms before, so I googled around to find out what is checked and unchecked exception. I didn't find anything related to this kind of exception in Python.

Do we have a concept of checked and unchecked exceptions in Python? If no, then by default all the exceptions are checked or unchecked?

Thank you in advance!

2 Answers

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!

Java have checked and unchecked exceptions because Java is a complied programming language, checked exception comes in compiling. In python, there is no such exception because Python is an interpreted language.

Related