Python Exception Handling Tutorial

When a Python application encounters an error, it halts the execution of the remaining code. Errors in Python can arise from either a syntactical mistake in an expression or a Python exception. In this tutorial, we will explore the concept of exceptions. Additionally, we will differentiate between a syntax error and an exception. Following this, we will delve into the use of try and except blocks, as well as how to raise exceptions and implement assertions. Finally, we will review the list of Python exceptions.

What is an Exception?

In Python, an exception refers to an event that occurs during the execution of a program, leading to an interruption in the normal flow of the program's operations. When the Python interpreter encounters a situation that it cannot manage, it generates an exception. An exception is essentially an object in Python that characterizes an error condition.

When an exception occurs in Python code, there are two possible actions: either address the exception right away or terminate and exit the program.

Exceptions versus Syntax Errors

When the interpreter encounters a statement that contains an error, syntax errors are triggered. Let’s examine the following situation:

Example

#Python code after removing the syntax error

string = "Python Exceptions"

for s in string:

    if (s != o:

        print( s )

Output:

Output

if (s != o:

              ^

SyntaxError: invalid syntax

The arrow in the output indicates the location where the interpreter detected a syntax error. In this instance, there was an unmatched bracket. Ensure that it is closed and then execute the program again:

Example

#Python code after removing the syntax error

string = "Python Exceptions"

for s in string:

    if (s != o):

        print( s )

Output:

Output

2 string = "Python Exceptions"

      4 for s in string:

----> 5     if (s != o):

      6         print( s )

NameError: name 'o' is not defined

An exception error was encountered following the execution of this code. This type of error occurs when syntactically correct Python code results in a failure. The final line of the output indicated the specific name of the exception error that was experienced. Rather than simply stating "exception error," Python provides details about the nature of the exception error that took place. In this case, it was a NameError. Python comes with a variety of built-in exceptions. Additionally, it allows for the creation of user-defined exceptions.

Try and Except Statement - Catching Exceptions

In Python, exceptions are captured and managed through the utilization of try and except blocks. The try section encompasses the code that has the potential to trigger an exception, whereas the except section comprises the lines of code that address the exception. Let's explore an example where we attempt to access an index in an array that exceeds its length, and subsequently manage the exception that arises from this action.

Example

# Python code to catch an exception and handle it using try and except code blocks

a = ["Python", "Exceptions", "try and except"]

try:

    #looping through the elements of the array a, choosing a range that goes beyond the length of the array

     for i in range( 4 ):

        print( "The index and element from the array is", i, a[i] )

#if an error occurs in the try block, then except block will be executed by the Python interpreter

except:

    print ("Index out of range")

Output:

Output

The index and element from the array is 0 Python

The index and element from the array is 1 Exceptions

The index and element from the array is 2 try and except

Index out of range

The segments of code that may generate an error are placed within the try block in the example provided earlier. When the value of i exceeds 2, it tries to access an element of the list that is beyond its available length, which leads to an exception. Subsequently, the except block captures this exception and allows the code to run without interruption.

How to Raise an Exception

In cases where a condition fails to satisfy our specified criteria, yet is still deemed valid by the Python interpreter, we have the option to deliberately trigger an exception by utilizing the raise keyword. This approach allows us to implement a custom exception alongside the raise statement.

If we intend to utilize the raise statement to trigger an exception upon the occurrence of a specific condition, we can accomplish this in the following manner:

Example

#Python code to show how to raise an exception in Python

num = [3, 4, 5, 7]

if len(num) > 3:

    raise Exception( f"Length of the given list must be less than or equal to 3 but is {len(num)}" )

Output:

Output

1 num = [3, 4, 5, 7]

      2 if len(num) > 3:

----> 3     raise Exception( f"Length of the given list must be less than or equal to 3 but is {len(num)}" )

Exception: Length of the given list must be less than or equal to 3 but is 4

The execution halts and displays our exception in the output, offering insights into what has gone wrong.

Assertions in Python

Upon completing the verification of the program, an assertion serves as a consistency check that can be enabled or disabled at will.

The most straightforward method to grasp the concept of an assertion is to liken it to an if-then statement. When an expression is assessed, an exception is raised if the result evaluates to false.

Assertions are implemented through the assert statement, a feature that was introduced in Python version 1.5 as a new keyword.

Assertions are frequently utilized at the start of a function to verify that the input is valid, as well as at the conclusion of the function call to ensure that the output is also valid.

The assert Statement

Python evaluates the neighboring expression, typically expecting it to be true when an assert statement is encountered. If the evaluation of the expression yields false, Python raises an AssertionError exception.

The syntax for the assert clause is −

Example

assert Expressions[, Argument]

In Python, when an assertion fails, it raises an AssertionError, which includes the ArgumentException as its argument. To manage and respond to AssertionError exceptions effectively, we can utilize the try-except block. However, if these exceptions are not caught, the execution of the program will terminate, leading the Python interpreter to produce a traceback.

Example

#Python program to show how to use assert keyword

# defining a function

def square_root( Number ):

    assert ( Number < 0), "Give a positive integer"

    return Number**(1/2)

#Calling function and passing the values

print( square_root( 36 ) )

print( square_root( -36 ) )

Output:

Output

7 #Calling function and passing the values

----> 8 print( square_root( 36 ) )

      9 print( square_root( -36 ) )

Input In [23], in square_root(Number)

      3 def square_root( Number ):

----> 4     assert ( Number < 0), "Give a positive integer"

      5     return Number**(1/2)

AssertionError: Give a positive integer

Try with Else Clause

Python provides the functionality of an else clause that must follow every except clause within the try and except blocks. The else block is executed only when the try clause does not raise an exception, allowing the Python interpreter to proceed to the else section under these circumstances.

Below is an example of a try block that includes an else clause.

Example

# Python program to show how to use else clause with try and except clauses

# Defining a function which returns reciprocal of a number

def reciprocal( num1 ):

    try:

        reci = 1 / num1

    except ZeroDivisionError:

        print( "We cannot divide by zero" )

    else:

        print ( reci )

# Calling the function and passing values

reciprocal( 4 )

reciprocal( 0 )

Output:

Output

0.25

We cannot divide by zero

Finally Keyword in Python

In Python, the finally keyword is utilized and is consistently placed following the try-except structure. The code contained within the finally block is guaranteed to run after the completion of the try block, regardless of whether it concluded successfully or was interrupted due to an exception or other factors.

Below is an illustration of the usage of the finally keyword in conjunction with try-except blocks:

Example

# Python code to show the use of finally clause

# Raising an exception in try block

try:

    div = 4 // 0

    print( div )

# this block will handle the exception raised

except ZeroDivisionError:

    print( "Atepting to divide by zero" )

# this will always be executed no matter exception is raised or not

finally:

    print( 'This is code of finally clause' )

Output:

Output

Atepting to divide by zero

This is code of finally clause

User-Defined Exceptions

Through the process of extending the standard built-in exceptions, Python enables us to create our own tailored exceptions.

The following example demonstrates a RuntimeError. In this scenario, a custom class that extends RuntimeError is created. When an exception is identified, this custom class can be utilized to provide further specific details regarding the error.

In the try block, we invoke a user-defined exception, and subsequently, we manage this exception in the except block. For instance, we instantiate the class EmptyError by utilizing the variable var.

Example

class EmptyError( RuntimeError ):

   def __init__(self, argument):

      self.arguments = argument

Once the preceding class has been created, the following is how to raise an exception:

Code

var = " "

try:

    raise EmptyError( "The variable is empty" )

except (EmptyError, var):

    print( var.arguments )

Output:

Output

2 try:

----> 3     raise EmptyError( "The variable is empty" )

      4 except (EmptyError, var):

EmptyError: The variable is empty

Python Exceptions List

Presented below is a comprehensive compilation of the built-in exceptions available in Python.

Sr.No. Name of the Exception Description of the Exception
1 Exception All exceptions of Python have a base class.
2 StopIteration If the next() method returns null for an iterator, this exception is raised.
3 SystemExit The sys.exit() procedure raises this value.
4 StandardError Excluding the StopIteration and SystemExit, this is the base class for all Python built-in exceptions.
5 ArithmeticError All mathematical computation errors belong to this base class.
6 OverflowError This exception is raised when a computation surpasses the numeric data type's maximum limit.
7 FloatingPointError If a floating-point operation fails, this exception is raised.
8 ZeroDivisionError For all numeric data types, its value is raised whenever a number is attempted to be divided by zero.
9 AssertionError If the Assert statement fails, this exception is raised.
10 AttributeError This exception is raised if a variable reference or assigning a value fails.
11 EOFError When the endpoint of the file is approached, and the interpreter didn't get any input value by raw_input() or input() functions, this exception is raised.
12 ImportError This exception is raised if using the import keyword to import a module fails.
13 KeyboardInterrupt If the user interrupts the execution of a program, generally by hitting Ctrl+C, this exception is raised.
14 LookupError LookupErrorBase is the base class for all search errors.
15 IndexError This exception is raised when the index attempted to be accessed is not found.
16 KeyError When the given key is not found in the dictionary to be found in, this exception is raised.
17 NameError This exception is raised when a variable isn't located in either local or global namespace.
18 UnboundLocalError This exception is raised when we try to access a local variable inside a function, and the variable has not been assigned any value.
19 EnvironmentError All exceptions that arise beyond the Python environment have this base class.
20 IOError If an input or output action fails, like when using the print command or the open() function to access a file that does not exist, this exception is raised.
22 SyntaxError This exception is raised whenever a syntax error occurs in our program.
23 IndentationError This exception was raised when we made an improper indentation.
24 SystemExit This exception is raised when the sys.exit() method is used to terminate the Python interpreter. The parser exits if the situation is not addressed within the code.
25 TypeError This exception is raised whenever a data type-incompatible action or function is tried to be executed.
26 ValueError This exception is raised if the parameters for a built-in method for a particular data type are of the correct type but have been given the wrong values.
27 RuntimeError This exception is raised when an error that occurred during the program's execution cannot be classified.
28 NotImplementedError If an abstract function that the user must define in an inherited class is not defined, this exception is raised.

Summary

We learned about different methods to raise, catch, and handle Python exceptions after learning the distinction between syntax errors and exceptions. We learned about these clauses in this tutorial:

  • We can throw an exception at any line of code using the raise keyword.
  • Using the assert keyword, we may check to see if a specific condition is fulfilled and raise an exception if it is not.
  • All statements are carried out in the try clause until an exception is found.
  • The try clause's exception(s) are detected and handled using the except function.
  • If no exceptions are thrown in the try code block, we can write code to be executed in the else code block.

Below is the structure for the try, except, else, and finally blocks.

Syntax:

Example

try:

    # Code block

    # These statements are those which can probably have some error

except:

    # This block is optional.

    # If the try block encounters an exception, this block will handle it.

else:

    # If there is no exception, this code block will be executed by the Python interpreter

finally:

    # Python interpreter will always execute this code.

Input Required

This code uses input(). Please provide values below: