Displaying Information for Thrown and Caught Exceptions to the User in Python
Exception Semantics in Python
Exception handling refers to how a program reacts when unexpected events, known as exceptions, occur throughout the program's execution.
Exception semantics varies considerably among programming languages. Based on this, we can divide programming languages into two groups:
- Programming languages that only employ exceptions to address exceptional, unforeseen, or incorrect circumstances, such as C++, Java, and C#.
- Programming languages that use exceptions as standard flow control structures, such as Ada, ML, OCaml, Python, and Ruby. For example, in Python, when an iterator has exhausted its output, and no more items can be generated, an exception of type StopIteration is thrown.
As a result, exceptions are pervasive in Python, and exception catching and handling is a must for writing robust Python code.
Displaying Information for Thrown and Caught Exceptions to the User
In many situations, it is beneficial to handle the exception and give a user a "loud and clear" message of what has happened as feedback. This is also particularly useful in investigating the root cause of the exception and whether it is the tip of the iceberg of a more significant latent bug.
This can be simplified by the fact that exceptions thrown by built-in functions, standard library functions, and functions in many well-tested third-party libraries all contain rich semantics in:
- The class of the exception. Given an exception
e
, it is accessible viatype(e)
, andtype(e).__name__
gives astr
representation. - The message of the exception. Given an exception
e
,str(e)
generates a representation of the argument(s) to the instance.
In command-line programs, we can write both of them to stderr
, as shown in the example below:
1 |
|
In GUI programs, we can display them in a message box, with the class of the exception being the title of the message box and the message of the exception being the message of the message box, as shown in the example below:
1 |
|
References
- https://en.wikipedia.org/wiki/Exception_handling#Exception_support_in_programming_languages
- https://docs.python.org/3/library/exceptions.html#bltin-exceptions