Skip to content

Instantly share code, notes, and snippets.

@jhazelwo
Last active December 2, 2024 13:29
Show Gist options
  • Save jhazelwo/86124774833c6ab8f973323cb9c7e251 to your computer and use it in GitHub Desktop.
Save jhazelwo/86124774833c6ab8f973323cb9c7e251 to your computer and use it in GitHub Desktop.
Supress traceback for custom Python exceptions
#!/usr/bin/env python3
""" -*- coding: utf-8 -*-
Example Python3 Raise Exception without Traceback
Example Python3 Hide Traceback
Python3 Custom Exception Class
Python3 custom exception suppress traceback example
Python3 custom exception without traceback example
Example Python Raise Exception without Traceback
Example Python Hide Traceback
Python Custom Exception Class
Python custom exception suppress traceback example
Python custom exception without traceback example
"""
import sys
class QuietError(Exception):
# All who inherit me shall not traceback, but be spoken of cleanly
pass
class ParseError(QuietError):
# Failed to parse data
pass
class ArgumentError(QuietError):
# Some other problem with arguments
pass
class TooMany(QuietError):
# Too many results returned or values to unpack
pass
def quiet_hook(kind, message, traceback):
if QuietError in kind.__bases__:
print('{0}: {1}'.format(kind.__name__, message)) # Only print Error Type and Message
else:
sys.__excepthook__(kind, message, traceback) # Print Error Type, Message and Traceback
sys.excepthook = quiet_hook
@OSHI7
Copy link

OSHI7 commented Dec 16, 2019

I'm workin` on this too. Did you find a nice way?

@bozhinov
Copy link

Thank you. Neat trick

@busla
Copy link

busla commented Dec 2, 2024

This also works

import sys

class CustomError(Exception):
    def __init__(self, message):
        super().__init__(message)
        self.__suppress_context__ = True
        sys.tracebacklimit = 0

raise CustomError("some error")

# output: some.module.CustomError: some error

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment