Raising exceptions during exceptional conditions
This example demonstrates how you raise a simple exception — that it doesn’t require anything special. The following steps simply create the exception and then handle it immediately.-
Open a Python File window.
You see an editor in which you can type the example code.
-
Type the following code into the window — pressing Enter after each line:
try: raise ValueError except ValueError: print("ValueError Exception!")
You wouldn’t ever actually create code that looks like this, but it shows you how raising an exception works at its most basic level. In this case, the raise call appears within a try … except block. A basic raise call simply provides the name of the exception to raise (or throw). You can also provide arguments as part of the output to provide additional information.
Notice that this try … except block lacks an else clause because there is nothing to do after the call. Although you rarely use a try … except block in this manner, you can. You may encounter situations like this one sometimes and need to remember that adding the else clause is purely optional. On the other hand, you must add at least one except clause.
-
Click Run Cell.
Python displays the expected exception text, as shown in the figure below.
Passing error information to the caller
Python provides exceptionally flexible error handling in that you can pass information to the caller (the code that is calling your code) no matter which exception you use. Of course, the caller may not know that the information is available, which leads to a lot of discussion on the topic.
You may have wondered whether you could provide better information when working with a ValueError exception than with an exception provided natively by Python. The following steps show that you can modify the output so that it does include helpful information.-
Open a Python File window.
You see an editor in which you can type the example code.
-
Type the following code into the window — pressing Enter after each line:
try: Ex = ValueError() Ex.strerror = "Value must be within 1 and 10." raise Ex except ValueError as e: print("ValueError Exception!", e.strerror)
The ValueError exception normally doesn’t provide an attribute named strerror (a common name for string error), but you can add it simply by assigning a value to it as shown. When the example raises the exception, the except clause handles it as usual but obtains access to the attributes using e. You can then access the e.strerror member to obtain the added information.
-
Click Run Cell.
You see a Python Shell window open. The application displays an expanded ValueError exception.