How to use Python built-in exception
Python raises an exception when a program terminates with an error. Python provides many built-in exceptions, which can be explored by running the following command:
print(dir(locals()['__builtins__']))
In the code, locals()['__builtins__'] returns a dictionary of all built-in Python exceptions, modules, and attributes, which we list down using the dir command.
The most popular classes of built-in exceptions are listed below:
The BaseException class
The BaseException class is the base of all built-in exceptions in Python. It serves as the root of the exception hierarchy. It includes exceptions like SystemExit, KeyboardInterrupt, and GeneratorExit, which are used for special-purpose exceptions. Usually, we do not catch BaseException directly in our code unless there is a specific need.
The Exception class
Exception is the derived class from BaseException. It is the common base class for all non-system exiting exceptions. Most of the built-in exceptions that we encounter fall under the Exception class. Some of the commonly occurring errors derived from the Exception class are given below:
| Raised when an error is encountered in an arithmetic operation |
| Raised when an assertion fails, indicating an unexpected condition |
| Raised when an attribute reference or assignment fails |
| Raised when an import statement fails to import a module |
| Raised when an operation fails due to insufficient memory |
| Raised when a local or global variable name is not found or defined |
| Raised when an operation or function is applied to an inappropriate data type |
| Raised when a function or operation receives an argument of the correct data type but an inappropriate value |
| Raised when a syntax error is encountered in the code |
Exception handling
In Python, we use the try and except blocks to handle exceptions. Below, we give the syntax to handle exceptions using the Exception class:
try:# Codeblockexcept Exception as e:print ("Error occurred" , e)
As discussed above, Exception provides access to all the non-system exiting exceptions. If we want to catch any error occurring in the try block, we simply use except Exception as e: as shown in the code block above. If we want to catch specific errors, we do so by explicitly writing the exception name in the except block. The syntax is given below:
try:# Codeblockexcept <exception-name> as e:print ("Error occurred" , e)
In line 3, we can substitute the <exception-name> with the exception name we want to catch explicitly. Some examples are given below:
ZeroDivisionError
ZeroDivisionError occurs when we try to divide a number by zero in our program. Click the "Run" button to see the ZeroDivisionError:
try:# Codeblockresult = 5 / 0 # Raises ZeroDivisionError: division by zeroprint(result)except ZeroDivisionError as e:print (e)
We can see the code explanation below:
Line 3: We divide 5 by 0, which raises the
ZeroDivisionError.Line 6: We define the
exceptblock with theZeroDivisionError.
IndexError
IndexError is raised when we try to access an item of a sequence (list, string, and tuple) using an invalid index. Click the "Run" button to see the IndexError:
try:# Codeblocklst = [1,2,3]print(lst[3])except IndexError as e:print (e)
We can see the code explanation below:
Line 4: We try to access an element at index 3, which raises the
IndexError: list index out of rangeerror.Line 5: We define the
exceptblock with theIndexError.
NameError
NameError exception is raised when we try to access a variable not defined in the current scope. Click the "Run" button to see the NameError:
try:# Codeblockprint(variable)except NameError as e:print (e)
We can see the code explanation below:
Line 3: We try to print
variablethat does not exist in our code which raisesNameError: name variable is not definederror.Line 6: We define the
exceptblock with theNameError.
TypeError
TypeError exception is raised when we try to perform operations or functions on variables with incompatible data types. Click the "Run" button to see the TypeError:
try:# Codeblockage = "Age" + 10result = int(age)except TypeError as e:print (e)
We can see the code explanation below:
Line 3: We try to concatenate two values, one (
Age) of string data type and the other (10) with an integer datatype. Concatenating two different data types is not possible; therefore, Python raises theTypeError:cannot concatenate 'str' and 'int' objectserror.Line 5: We define the
exceptblock with theTypeErrorexception.
ValueError
ValueError exception is raised when an operation or function receives a value of the correct data type, but the value itself is invalid for the operation. Click the "Run" button to see the ValueError:
try:# Codeblockresult = int("Age")except ValueError as e:print (e)
We can see the code explanation below:
Line 3: We try to convert a string (
Age) into an integer data type which is not possible, which raises theValueError.Line 4: We define the
exceptblock with theValueError.
RuntimeError
RuntimError exception is raised while a program is executing. It may occur due to issues related to memory allocation, accessing files, or external dependencies. Click the "Run" button to see the RecursionError:
def infinite_recursion(n):if n == 1:returnelse:n = n + 1infinite_recursion(n)try:# Codeblockinfinite_recursion(2)except RuntimeError as e:print (e)
We can see the code explanation below:
Lines 1–3: We define the
infinite_recursionrecursive function thatreturnifnhas a value of 1.Lines 4–6: If condition at line 2 is false, then we increment the value of
nby 1 and make a recursive call to theinfinite_recursionfunction.Lines 8–10: We make a call to
infinite_recursionfunction at line 10 withnequal to 2.Lines 11–12: We define the
exceptblock that executes if thetryblock raises an error.
Conclusion
There are many more built-in exceptions that we can explicitly define in our except block. We can get the list of all built-in exceptions using the command dir(locals()['__builtins__']). It is essential to know about the exceptions that might occur in a program application. This helps us handle them accurately using Python's built-in exceptions, resulting in the smooth functioning of the application.
Free Resources