2. Error messages
When an exception is caught, you can keep its exception object with as:
except ValueError as error:catches aValueErrorand assigns the exception object toerror.- The exception object carries the message that describes what went wrong.
print(error)prints that message: it callsstr(error), so the type name is not included.- The name after
asis a normal variable, but it only exists inside theexceptblock.str(error)gives you the message as a string. - If you do not know which exception may happen, catch
Exceptionand inspect it:type(error).__name__gives the type name as a string.
except Exception:catches almost any error. A bareexcept:also catches everything, but it hides bugs you did not expect, so avoid it.
Coming from JavaScript? A caught error exposes its text as error.message; in Python, use print(error) or str(error).
Print the exception message
Catch the ValueError raised by int("abc") with as error and print the exception object.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Put the message inside a sentence
Catch the ValueError raised by int("12.5") with as error. Print Failed: followed by the message using an f-string.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Read a division message
Put print(10 / 0) inside a try block. Catch ZeroDivisionError with as error and print the exception object.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Return the message from a function
Define describe_error(text) that tries to convert text with int(text) inside a try block. If it raises ValueError, catch it with as error and return str(error). If the conversion succeeds, return "ok". Print describe_error("ten").
Print exactly:
Create a free account to save your progress and unlock chapter 2.