Difference between except and except Exception as exc | Which one to use?

Difference between except and except Exception as exc | Which one to use?

If you look at the code, you might see two types of exceptions written in the Python code.

Code snippet 1

try:
  # code inside try block
except:
  # handling exception code 

Code snippet 2

try:
  # code inside try block
except Exception as exc:
  # handling exception code 

In this article, I will describe the difference between except and except Exception as exc, two exception-handling snippets, what’s the best Python coding practice to follow?

Difference between except and except Exception:

# 1

The second code snippet gives you an available variable (exc) in the except block that can be used to find/print/log actual exception messages.

try:
  # code inside try block
except Exception as exc:
  # handling exception code 
  print(f"Exception: {str(exc)}")

Above code snippet will print the exception message that depicts the actual reason for the exception.

You can use the exception information like type, message, stack trace, etc to handle the exception more significantly and precisely.

To explore further, you can check all the associated attributes to the exc variable using dir method.

try:
  # code inside try block
except Exception as exc:
  # handling exception code 
  print(dir(exc))

There is a lot of information you can access using exc exception variable.

The most common and useful attribute you can access is the message.

try:
  # code inside try block
except Exception as exc:
  # handling exception code 
  print(exc.message)

# 2

The downside of using a second snippet is that…

It does not catch the BaseException or system-related exceptions (like SystemExit, GeneratorExit) and input-output exceptions like KeyboardInterrupt exception.

The above exceptions is caught by the bare except (first code snippet).

If you want to capture all kinds of exceptions use BaseException.

try:
  # code inside try block
except BaseException as exc:
  # handling exception code 
  print(exc.message)

What is the Best practice to use exceptions?

This is one major question.

If you are doing a hobby project and don’t want to deal with exceptions, it’s okay if you use the first snippet code.

But still, I would suggest using the second snippet for exception handling in Python. With this, you can catch all desired exceptions (if not now, in the future) and also print the information or message associated with the exception. This way it is easy to identify any problem that occurs due to exceptions.

Any doubt? Write me in the comment.

Happy Coding!

Leave a Reply

Your email address will not be published. Required fields are marked *