DEV Community

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

Posted on

6 2

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!

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay