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:
BaseException
classThe 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.
Exception
classException
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 |
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 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 except
block with the ZeroDivisionError
.
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 range
error.
Line 5: We define the except
block with the IndexError
.
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 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
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 the TypeError:cannot concatenate 'str' and 'int' objects
error.
Line 5: We define the except
block with the TypeError
exception.
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 the ValueError
.
Line 4: We define the except
block with the ValueError
.
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_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.
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