DEV Community

Cover image for Handling errors like a pro in python with sys.excepthook😎
Vaarun Sinha
Vaarun Sinha

Posted on

Handling errors like a pro in python with sys.excepthook😎

As developers, whenever we code we encounter many errors and tracebacks.

So, how to handle this like a pro with sys.excepthook?

Well this is what we are going to explore in this blog, so let's began!

Let's Goo (GIF)

The Need

Whenever an error occurs the program prints that error and stops right?

But what if you want to mail that error to a developer or automatically open an issue in a GitHub issues?

Now many of you will say that we can do that with try and except blocks.

Yes you can but it would be pretty messy to surround try and except in a python file, or files for bigger projects.

But with sys.excepthook hook you just have to define a function to handle any error that might pop out.

What is sys.excepthook and what does it do?

You can use sys.excepthook to catch errors and do anything with them!

Excepthook be like:

Ladies and gentelmen we got him (GIF)

Basic Example



import sys

def imposter_syndrome(type, value, traceback):
    print("I am a bad coder ☹️")
    print(f"{type} of error has occurred, the value: {value}, and you can see traceback: {traceback}")

sys.excepthook = imposter_syndrome


Enter fullscreen mode Exit fullscreen mode

Try Running This Code:

This was a non-practical but easy to understand example, stay tuned for more real world examples!

Coder (GIF)

Happy Coding!

Top comments (0)