1

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.

Keexarian
  • 17
  • 5

2 Answers2

0

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.

mgilson
  • 300,191
  • 65
  • 633
  • 696
  • Yes, you'll always get the last error -- Of course, you can always add the original error as an attribute of the final error and tack it on in your exception handling. – mgilson Aug 19 '14 at 17:27
0

Firstly, never do a blank except. That will catch all errors, including things like KeyboardInterrupt - so you won't be able to ctrl-c out of your program. Here you should just catch MyError.

The except clause also allows you to assign the actual exception to a variable, which you can then print or do anything else with. So you can do:

try:
    ...
except MyError as e:
    print e.text 
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895