To catch any error in Python, use a generic try…except block with the Exception class. Here’s an example:
try:
# Code that may raise an error
risky_operation()
except Exception as e:
print(f”An error occurred: {e}”)
The Exception class catches most runtime errors, but it excludes system-exiting exceptions like SystemExit, KeyboardInterrupt, and GeneratorExit. If you need to handle all exceptions, including these, use except BaseException cautiously.
However, catching all exceptions can make debugging harder. It’s better to catch specific exceptions whenever possible to maintain code clarity and robustness.