Right now I just have a blank exception class. I was wondering how I can give it a variable when it gets raised and then retrieve that variable when I handle it in the try...except.
class ExampleException (Exception):
pass
Solution 1 What you need to do is declare your variable outside of the try scope. Before the try scope so it the variable still exists in your except block. This will raise the exception but x will still have scope (lifetime) and will print out in the 2nd exception case.
except ExceptionType, Argument: You can print value of Argument here... If you write the code to handle a single exception, you can have a variable follow the name of the exception in the except statement. If you are trapping multiple exceptions, you can have a variable follow the tuple of the exception.
The most common use of raise constructs an exception instance and raises it. When an exception is raised, no further statements in the current block of code are executed.
If an exception occurs during execution of the try clause, the exception may be handled by an except clause. If the exception is not handled by an except clause, the exception is re-raised after the finally clause has been executed.
Give its constructor an argument, store that as an attribute, then retrieve it in the except
clause:
class FooException(Exception): def __init__(self, foo): self.foo = foo try: raise FooException("Foo!") except FooException as e: print e.foo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With