Raise a custom Python exception and catch it, showing the original message.
You raise an exception with the raise keyword, giving it either a class or an instance to construct.
class InsufficientFundsError(Exception):
pass
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFundsError(f"cannot withdraw {amount} from {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, and the except clause catches it by type. The message is available on the instance, which is why str(err) gives the text back.
Two rules to know. The exception class must be a subclass of Exception — you cannot raise an arbitrary object, because raise requires something that can be treated as an exception. And when you want to add information to an existing exception, use the three-argument form: raise NewError("message") from original, which sets the cause explicitly and shows both exceptions in the traceback.
That last point is worth an example. If you catch a low-level error and re-raise a higher-level one, the original traceback is attached automatically as the context, so the traceback shows both. Writing from original makes that relationship explicit rather than implicit.
For an interview, the practical guidance is to raise exceptions with a message that says what went wrong and with what values, and to define your own exception classes for the failures callers are expected to handle.