0

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.

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
Can this be achieved without using the generic exception class "except Exception as err" ?
@flying_fluid_four yes, for that your code should throw a custom exception then it will be catch in except block, but your code is not throwing exception of type MyException. try this try: regex_pattern = re.compile(r'fiction') raise MyException("raising exception") # for book in books: # match_object = re.search(regex_pattern, booke) # print(match_object) except MyException as err: print("There was an error") print(err) raise MyException("There was an error")
1

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

Comments

0

I Was able to achieve the desired result by enhancing the custom exception class as follows (as per the accepted answer suggestion):

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

and then completely omitting the additional call in the except statement like so:

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:
            raise MyException("There was an error")



a = over.check()
print(a)

This would give me an error like so:

Traceback (most recent call last):
  File "compare.py", line 48, 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 "compare.py", line 59, in <module>
    a = over.check()
  File "compare.py", line 52, in check
    raise MyException("There was an error")
__main__.MyException: There was an error

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.