One has pretty much control on which information from the traceback to be displayed/logged when catching exceptions.
The code
with open["not_existing_file.txt", 'r'] as text:
pass
would produce the following traceback:
Traceback [most recent call last]:
File "exception_checks.py", line 19, in
with open["not_existing_file.txt", 'r'] as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
Print/Log the full traceback
As others already mentioned, you can catch the whole traceback by using the traceback module:
import traceback
try:
with open["not_existing_file.txt", 'r'] as text:
pass
except Exception as exception:
traceback.print_exc[]
This will produce the following output:
Traceback [most recent call last]:
File "exception_checks.py", line 19, in
with open["not_existing_file.txt", 'r'] as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
You can achieve the same by using logging:
try:
with open["not_existing_file.txt", 'r'] as text:
pass
except Exception as exception:
logger.error[exception, exc_info=True]
Output:
__main__: 2020-05-27 12:10:47-ERROR- [Errno 2] No such file or directory: 'not_existing_file.txt'
Traceback [most recent call last]:
File "exception_checks.py", line 27, in
with open["not_existing_file.txt", 'r'] as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
Print/log error name/message only
You might not be interested in the whole traceback, but only in the most important information, such as Exception name and Exception message, use:
try:
with open["not_existing_file.txt", 'r'] as text:
pass
except Exception as exception:
print["Exception: {}".format[type[exception].__name__]]
print["Exception message: {}".format[exception]]
Output:
Exception: FileNotFoundError
Exception message: [Errno 2] No such file or directory: 'not_existing_file.txt'
How do I print a try catch error?
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 error messages in Python?
message [at least in Python 2.7. 12]. If you want to capture the error message, use str[e] , as in the other answers.
How do I print exception details 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 exception messages in Python 3?
Python3. Method 2: By using print_exception[] method. This method prints exception information and stack trace entries from traceback object tb to file.