Reading Time: 1 minutes
Raising your own Exceptions in Python
The raise keyword is used to explicitly raise an exception. This is in contrast to when you make a mistake in your code, because then the exception is raised implicitly. Here, you are deliberately raising an exception. The raise keyword is useful in 2 scenarios, one is for reraising the exception, and other is for using exception for error-checking. The following code snippet will elaborate more on these 2 scenarios and other details related to the raise keyword.
######### RERAISING AN EXCEPTION: raise ########### # The raise keyword in this situation is found in the except clause, as a standalone keyword. This is used when you want to do some processing in the except clause before you re-raise the most recently caught exception, also known as active exception. >>> import io >>> try: fh = open('someExistentFile.txt', 'r') fh.write("Attempting to write to a file opened in read-only mode.") except io.UnsupportedOperation: fh.close() print("File closed?", fh.closed) raise File closed? True Traceback (most recent call last): File "<pyshell#292>", line 3, in <module> fh.write("Attempting to write to a file opened in read-only mode.") io.UnsupportedOperation: not writable ######### ERROR CHECKING: raise ExceptionName(“Optional message string.”) ########### # You can intentionally raise errors as part of error-checking. The raise keyword is followed by the Exception to be thrown if a particular check fails. You can even pass a custom message to provide a situation-specific explanation to the user. >>> temperature = 450 >>> if temperature > 400: raise ValueError() Traceback (most recent call last): File "<pyshell#257>", line 2, in <module> raise ValueError() ValueError >>> >>> >>> >>> if temperature > 400: raise ValueError("Temperature greater than 400 degrees!!! CODE GREEN! CODE GREEN!") Traceback (most recent call last): File "<pyshell#262>", line 2, in <module> raise ValueError("Temperature greater than 400 degrees!!! CODE GREEN! CODE GREEN!") ValueError: Temperature greater than 400 degrees!!! CODE GREEN! CODE GREEN! # You can choose from common builtin Exceptions and just supply a custom message string, as we did in the above example. And if there is no suitable builtin Exception, you can make your own exception in the following fashion: ############ CREATING AN EXCEPTION OBJECT FROM AN EXISTING EXCEPTION TYPE ############# >>> TemperatureError = ValueError() >>> raise TemperatureError Traceback (most recent call last): File "<pyshell#220>", line 1, in <module> raise TemperatureError ValueError >>> TemperatureError = ValueError("Temperature greater than 400 degrees!!! CODE GREEN! CODE GREEN!") >>> raise TemperatureError Traceback (most recent call last): File "<pyshell#246>", line 1, in <module> raise TemperatureError ValueError: Temperature greater than 400 degrees!!! CODE GREEN! CODE GREEN! >>> def check_temperature(temperature): if temperature < 45: raise TemperatureError print("Temperature under control.") >>> check_temperature(450) Traceback (most recent call last): File "<pyshell#249>", line 1, in <module> check_temperature(450) File "<pyshell#248>", line 3, in check_temperature raise TemperatureError File "C:\Python34\lib\idlelib\run.py", line 353, in runcode exec(code, self.locals) File "<pyshell#246>", line 1, in <module> raise TemperatureError ValueError: Temperature greater than 400 degrees!!! CODE GREEN! CODE GREEN! # Note that even though you are raising TemperatureError, the exception that is raised is ValueError. This is because all Exceptions are actually classes(parent of all these is the class called Exception), and classes can be instantiated i.e. objects can be made out of them. The very first line of the example (TemperatureError = ValueError()) is creating an instance/object called TemperatureError of the class ValueError. If you wish to create your own Exception class, you can do that in the following way. It is a brief write-up, which can be extended based on your knowledge of object-oriented concepts. ############# CREATING CUSTOM EXCEPTION CLASS DERIVED FROM THE PARENT CLASS OF ALL EXCEPTION CLASSES i.e. Exception. ########## >>> class TemperatureError(Exception): pass >>> myCustomExceptionObject = TemperatureError("Temperature greater than 400 degrees!!! CODE GREEN! CODE GREEN!") >>> def check_temperature(temperature): if temperature > 400: raise myCustomExceptionObject print("Temperature under control.") >>> check_temperature(450) Traceback (most recent call last): File "<pyshell#309>", line 1, in <module> check_temperature(450) File "<pyshell#308>", line 3, in check_temperature raise myCustomExceptionObject TemperatureError: Temperature greater than 400 degrees!!! CODE GREEN! CODE GREEN! # Note that some other languages like Java use the keyword throw instead of raise for the same functionality.