-1

In response to being able to override assertion error, someone suggested I do this.

Can anyone help me on how I can override the AssertionError class so that I can do an AssertionError and it will call my custom one such as the one in the picture?

nofinator
  • 2,906
  • 21
  • 25
  • What happens when you try that solution? What is the result you would like? – nofinator Jun 11 '19 at 16:35
  • 1
    Possible duplicate of [Proper way to declare custom exceptions in modern Python?](https://stackoverflow.com/questions/1319615/proper-way-to-declare-custom-exceptions-in-modern-python) – Tom Lubenow Jun 11 '19 at 16:37
  • It may help to answer the question if you provide some additional context about what you're trying to achieve and why you think you need to do this. Assertions in Python have a very specific intended purpose and it's likely that either you're missing the point or there is some better way of accomplishing your goal. – Brandon Tweed Jun 11 '19 at 16:43

2 Answers2

1

You can't override default exceptions but you can create a new exception class with the same name and import it in the file where you want to use it as shown in the image you have shared.

For example:

custom_exception.py


class CustomAssertionError(Exception): 

    # Constructor or Initializer 
    def __init__(self, message): 
        # do your stuff here
        raise AssertionError(message)

usage.py

from custom_exception import AssertionError

def my_function():
    raise CustomAssertionError("some error message")

For more details about creating custom exceptions in python please follow: Proper way to declare custom exceptions in modern Python?

Lavish
  • 461
  • 1
  • 4
  • 12
0

Here is a way to do this. It is ugly, and probably not very much recommended, but it works: (Note, this works in Python3, Python2.7 is different)

Example IPython code on how to override the builtin AssertionError class

lorg
  • 1,160
  • 1
  • 10
  • 27