Search code examples
pythonexceptiontry-catchuser-definedraise

Get raised error in a class to main()


Hi im currently doing a program like this.

class MyError(Exception):
    def __init__(self, text = "Correct")
        self.text = text
    def __str__(self):
        return (self.kod)

class Atom(self):
.
.
.
    try:
        function()
    else:
        raise MyError("Incorrect use of function")


def main():
    try:
        a = Atom()
    except:
        # Here i want to print the error that was raised

What I think I understand is that the error is raised in an object created in Atom(). But I want to send it to my main program and do the print of the error MyError there. Is it possible to do this and how should I write it so that the correct text of exception is printed since i will have several different error messages.

If i come to the except statement I would want to get the message "Incorrect use of function" printed.


Solution

  • It seems that you're pretty close:

    class MyError(Exception):
        def __init__(self, text = "Correct")
            self.text = text
        def __str__(self):
            return (self.kod)
    
    class Atom(self):
    .
    .
    .
        try:
            function()
        except:  # try: ... else: raise ... seems a bit funky to me.
            raise MyError("Incorrect use of function")
    
    
    def main():
        try:
            a = Atom()
        except Exception as err:  # Possibly `except MyError as err` to be more specific
            print err
    

    The trick is that when you catch the error, you want to bind the exception instance to a name using the as clause. Then you can print it, look at it's attributes, re-raise or pretty much do anything you choose with it.


    Please note that this code still isn't "clean". Generally, you want to limit exception handling as much as possible -- only catch exceptions that expect to see and that you know how to handle. Otherwise, you can sometimes mask hard to find bugs in your code. Because of this:

    try:
        do_something()
    except:
        ...
    

    is discouraged (it catches all sorts of things like KeyboardInterrupt and SystemExit) ... Instead:

    try:
        do_something()
    except ExceptionIKnowHowToHandle:
        ...
    

    is advised.