Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store exception body in variable

Is there a way to execute a try statement and return the error body as a variable?

i.e.

var = ''
try:
    error generating code
except:
    var = exception_body
like image 665
jonathan topf Avatar asked Jan 17 '12 20:01

jonathan topf


People also ask

How do you handle FileExistsError?

The Python "FileExistsError: [Errno 17] File exists" occurs when we try to create a directory that already exists. To solve the error, set the exist_ok keyword argument to True in the call to the os.

How do I get exception to text in Python?

The most common method to catch and print the exception message in Python is by using except and try statement. You can also save its error message using this method. Another method is to use logger.

How do you raise a specific exception in Python?

As a Python developer you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword.


1 Answers

Yes, use the as syntax of except:

try:
    raise Exception("hello world")
except Exception as x:
    print(x)

In earlier versions of Python, this would be written except Exception, x: which you may see from time to time.

like image 160
Greg Hewgill Avatar answered Oct 16 '22 05:10

Greg Hewgill