27 Oct 2019
Allows you to differentiate between various errors and deliver accurate error messages, making issue identification and resolution more efficient
try:
# some code
except FileNotFoundError:
# handle file not found
except IndexError
# handle index error
Utilizing the logging module you can capture exceptions along with vital information like timestamps, error details, stack traces
import logging
logging.basicConfig(filename'error.log', level=logging.ERROR)
try:
# some code
except Exception as e:
logging.error('An error occurred: %s', str(e))
Better code readability, improved error handling and modular project development.
finally
for Cleanup TasksEnsures that the code will execute regardless of whether an exception occurred or not.
try:
# code that may raise an exception
except Exception as e:
# handle it
else:
# code that executes if no exceptions are raised
finally:
# code that will always execute