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
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.
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.
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.
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.
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.
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