You can associate a message with an exception when you raise it. Builtin exceptions often have messages associated with them already.
To get the message when you catch the exception, just give it a name with the as keyword.
def raise_exception(): text = input("Enter 'error' to raise an exception: ") if text == "error": raise Exception("Oh no, an exception!") def main(): try: raise_exception() except Exception as e: print(e) main()
Enter 'error' to raise an exception: error Oh no, an exception!Enter 'error' to raise an exception: error Oh no, an exception!
‘e‘ in this code is a variable we’re using to refer to the exception itself.
When we pass the exception object to print, the __str__ method of the exception gets invoked to turn it into a string for printing.