Chapter 12: Problem 8
How do you retrieve an error message from an exception?
Short Answer
Expert verified
Answer: In Python, you can catch exceptions using the "try" and "except" keywords. The "try" block contains the code that may raise an exception, while the "except" block contains the code that will be executed when an exception occurs. To retrieve an error message from an exception, catch the exception with the "except" keyword followed by the exception type and an alias. Then, use the 'str()' function to convert the exception object into a string to retrieve the error message. For example:
```python
try:
result = 10 / 0
except ZeroDivisionError as e:
error_message = str(e)
print(f"An error occurred: {error_message}")
```