Home > OS >  Print custom error message using manually created exception class
Print custom error message using manually created exception class

Time:05-27

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.

CodePudding user response:

You should be using except NameError rather than except MyException, since the undefined variable causes a NameError to be raised.

To clarify, this:

except MyException:

should be

except NameError:

This outputs:

There was an error
Traceback (most recent call last):
  File "<string>", line 11, in check
NameError: name 'books' is not defined

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<string>", line 21, in <module>
  File "<string>", line 17, in check
__main__.MyException

CodePudding user response:

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

  • Related