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:

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:

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:

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:

We can see the code explanation below:

  • Line 3: We divide 5 by 0, which raises the ZeroDivisionError.

  • Line 6: We define the except block with the ZeroDivisionError.

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:

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 range error.

  • Line 5: We define the except block with the IndexError.

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:

We can see the code explanation below:

  • Line 3: We try to print variable that does not exist in our code which raises NameError: name variable is not defined error.

  • Line 6: We define the except block with the NameError.

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:

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 the TypeError:cannot concatenate 'str' and 'int' objects error.

  • Line 5: We define the except block with the TypeError exception.

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:

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 the ValueError.

  • Line 4: We define the except block with the ValueError.

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:

We can see the code explanation below:

  • Lines 1–3: We define the infinite_recursion recursive function that return if n has a value of 1.

  • Lines 4–6: If condition at line 2 is false, then we increment the value of n by 1 and make a recursive call to the infinite_recursion function.

  • Lines 8–10: We make a call to infinite_recursion function at line 10 with n equal to 2.

  • Lines 11–12: We define the except block that executes if the try block 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

Copyright ©2025 Educative, Inc. All rights reserved