Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a variable to an exception when raised and retrieve it when excepted?

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
like image 307
Takkun Avatar asked Jul 08 '11 15:07

Takkun


People also ask

How do you make a variable inside a try except block public?

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.

How arguments can be passed to an exception explain with an example?

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.

What happens after an exception is raised?

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.

What happens when an exception is raised and the program does not handle it with a try except statement?

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.


1 Answers

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 
like image 190
Fred Foo Avatar answered Oct 16 '22 19:10

Fred Foo