Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert exception error to string

Tags:

python

I want to work with the error message from an exception but can't seem to convert it to a string. I've read the os library man page but something is not clicking for me.

Printing the error works:

try:     os.open("test.txt", os.O_RDONLY) except OSError as err:     print ("I got this error: ", err) 

But this does not:

try:     os.open("test.txt", os.O_RDONLY) except OSError as err:     print ("I got this error: " + err)  TypeError: Can't convert 'FileNotFoundError' object to str implicitly 
like image 752
dpetican Avatar asked Jun 07 '16 16:06

dpetican


People also ask

How do you Stringify exceptions in Python?

If you are going to print the exception, it is better to use print(repr(e)) ; the base Exception. __str__ implementation only returns the exception message, not the type. Or, use the traceback module, which has methods for printing the current exception, formatted, or the full traceback.

How do I print an exception message in Python?

To catch and print an exception that occurred in a code snippet, wrap it in an indented try block, followed by the command "except Exception as e" that catches the exception and saves its error message in string variable e . You can now print the error message with "print(e)" or use it for further processing.

How do you catch errors in Python?

The try block lets you test a block of code for errors. The except block lets you handle the error. The else block lets you execute code when there is no error.

How do I raise an exception?

The raise keyword is used to raise an exception. You can define what kind of error to raise, and the text to print to the user.


1 Answers

In my experience what you want is repr(err), which will return both the exception type and the message.

str(err) only gives the message.

like image 102
Hendy Irawan Avatar answered Oct 09 '22 06:10

Hendy Irawan