Python allows for a programmer to create new exceptions if the project warrants them. However, make sure that one of the built-in exceptions won't do the job for you. They have been tested and tweaked over the years and not only do they work effectively, but they have been optimized for performance and are bug-free.
Making your own exceptions involves object-oriented programming, which will be covered in Chapter 4, Functions and Object Oriented Programming, in the Classes, methods, and namespaces section. To make a custom exception, the programmer determines which base exception to use as the class to inherit from. For example, making an exception for negative numbers or one for imaginary numbers would probably fall under the ArithmeticError exception class.
To make a custom exception, simply inherit the base exception and define what it will do. The following example gives an example of creating a custom exception:
1 import math 2 3 class NegativeNumberError(ValueError): 4 """Attempted improper operation on negative number.""" 5 pass 6 7 def squareRoot(number): 8 """Computes square root of number. Raises NegativeNumberError if number is less than 0.""" 9 if number < 0: 10 raise NegativeNumberError("Square root of negative number not permitted") 11 12 return math.sqrt(number) 13 14 if __name__ == "__main__": 15 squareRoot(-3)
Because this is dealing with square roots, we need to import the math module in line 1. We inherit from ValueError in line 3, creating the new class, NegativeNumberError. Because we are inheriting all the characteristics of ValueError, we don't have to do anything else, so we just use pass in line 5 to tell Python to continue with the program.
To actually use the new exception, a function is created in lines 7-12 that calls NegativeNumberError if the argument value is less than 0; otherwise, it gives the square root of the number.
Line 14 tells Python to run everything following if this program is explicitly called; that is, if this is the main program to be processed. Line 15 is just a test to ensure that the new exception works as expected.
Following screenshot shows the output of this program, showing that the new exception works as advertised: