pythonexceptioncustom-error-handling

Print custom error message using manually created exception class


I have a custom exception class as:

class MyException(Exception):
    pass

And I am invoking it as follows:

class over():

    def check():        
        col1 = 'ageminusone'
        col2 = 'Age'
        col3 = 'Flag'

        data = [['tom', 10], ['nick', 15], ['juli', 14]]
        df = pd.DataFrame(data, columns = ['Name', 'Age'])


        df[col1] = df.loc[0,col2] - 1

        books = ['romance',  'fiction']

        try:
            regex_pattern = re.compile(r'fiction')  
            for book in books:
                match_object = re.search(regex_pattern, booke)
                print(match_object)

        except MyException:
            print("There was an error")
            raise MyException



a = over.check()
print(a)

I get only the traceback error in the log, not the custom message "There was an error" like so:

Traceback (most recent call last):
  File "compare.py", line 53, in <module>
    a = over.check()
  File "compare.py", line 41, in check
    match_object = re.search(regex_pattern, booke)
NameError: name 'booke' is not defined

How can I modify this code to print "There was an error" before the actual traceback?

Note: The ask is not to use the generic "Exception" like:

try:
  yada yada 
except Exception as err:
  ...

I have to use MyException.


Solution

  • try this code:

    class MyException(Exception): """ Catches the exception raised by MyClass """

    def __init__(self, message):
        self.message = message
    
    def __str__(self):
        return self.message
    

    class over():

    def check(self):
        col1 = 'ageminusone'
        col2 = 'Age'
        col3 = 'Flag'
    
        data = [['tom', 10], ['nick', 15], ['juli', 14]]
        df = pd.DataFrame(data, columns = ['Name', 'Age'])
    
    
        df[col1] = df.loc[0,col2] - 1
    
        books = ['romance',  'fiction']
    
        try:
            regex_pattern = re.compile(r'fiction')
            for book in books:
                match_object = re.search(regex_pattern, booke)
                print(match_object)
    
        except Exception as err:
            print("There was an error")
            raise MyException("There was an error")
    

    obj = over()

    obj.check()

    output ::

    There was an error Traceback (most recent call last): File "C:\Users\jthakkar\Downloads\sp\Task\StackOverflow1.py", line 31, in check match_object = re.search(regex_pattern, booke) NameError: name 'booke' is not defined

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last): File "C:\Users\jthakkar\Downloads\sp\Task\StackOverflow1.py", line 40, in obj.check() File "C:\Users\jthakkar\Downloads\sp\Task\StackOverflow1.py", line 37, in check raise MyException("There was an error") main.MyException: There was an error