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:

ArithmeticError

Raised when an error is encountered in an arithmetic operation

AssertionError

Raised when an assertion fails, indicating an unexpected condition

AttributeError

Raised when an attribute reference or assignment fails

ImportError

Raised when an import statement fails to import a module

MemoryError

Raised when an operation fails due to insufficient memory

NameError

Raised when a local or global variable name is not found or defined

TypeError

Raised when an operation or function is applied to an inappropriate data type

ValueError

Raised when a function or operation receives an argument of the correct data type but an inappropriate value

SyntaxError

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:
# Codeblock
except Exception as e:
print ("Error occurred" , e)
Code to catch all errors occuring in the try block

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:
# Codeblock
except <exception-name> as e:
print ("Error occurred" , e)
Syntax to explicitly define the error we want to catch in the try block

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:
# Codeblock
result = 5 / 0 # Raises ZeroDivisionError: division by zero
print(result)
except ZeroDivisionError as e:
print (e)
Code to handle ZeroDivisionError exception

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:

try:
# Codeblock
lst = [1,2,3]
print(lst[3])
except IndexError as e:
print (e)
Code to handle IndexError exception

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:

try:
# Codeblock
print(variable)
except NameError as e:
print (e)
Code to handle NameError exception

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:

try:
# Codeblock
age = "Age" + 10
result = int(age)
except TypeError as e:
print (e)
Code to handle TypeError exception

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:

try:
# Codeblock
result = int("Age")
except ValueError as e:
print (e)
Code to handle ValueError exception

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:

def infinite_recursion(n):
if n == 1:
return
else:
n = n + 1
infinite_recursion(n)
try:
# Codeblock
infinite_recursion(2)
except RuntimeError as e:
print (e)
Code to handle RuntimeError exception

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 ©2024 Educative, Inc. All rights reserved