Raise a custom Python exception and catch it, showing the original message.
You raise an error with the raise keyword, and you give it either the class itself or an instance of that class.
class InsufficientFundsError(Exception):
pass
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFundsError('cannot withdraw ' + str(amount) + ' from ' + str(balance))
return balance - amount
try:
withdraw(50, 80)
except InsufficientFundsError as err:
print('Error:', err)
The raise statement creates an instance of the exception class using the message you gave it, and the except clause catches that instance by its type. The message stays on the instance, which is why str(err) gives the text back to you.
There are two rules worth remembering. The exception class must be a subclass of Exception, because you cannot raise an arbitrary object and Python needs something that can be treated as an error. And when you want to add information to an error that already happened, use the three-part form raise NewError('message') from original, which sets the cause on purpose and shows both errors in the traceback.
That last point is worth an example. If you catch a low-level error and raise a higher-level one, Python attaches the original traceback automatically as the context, so the traceback shows both errors. Writing from original makes that relationship clear instead of leaving it implied.
For an interview, the practical advice is to raise errors with a message that says what went wrong and with which values, and to define your own exception classes for the failures that callers are expected to handle.