Javaexercise.com

Exception Handling in Python

Python is a high-level, interpreted programming language, and is one of the most popular programming languages present in the software industry. One of the most important concepts in python is that of exception handling. Let us have a look at it in detail.

What is exception handling in Python?

In python, errors are usually of two broad categories - syntax errors and exceptions.

Syntax errors are fairly straightforward to identify and deal with by correcting any incorrect syntax.

Python raises exceptions whenever the program is syntactically correct but results in a runtime error nevertheless due to some special event being triggered.

Exception handling is basically performed to work around such unusual circumstances in a program that would usually block the flow of execution.

Let us look at some of the different exceptions in python.

NameError - This exception occurs when you try to reference a variable that has not been initialized before - locally or globally.

ZeroDivisionError - This exception occurs when you try to divide any number by zero.

IOError - This exception occurs when any unusual situation arises during input or output handling.

IndentationError - This exception occurs when the programmer does not align with the indentation rules of python.

EOFError - This exception occurs when operations are being performed even when the end of the file has been reached.

Let us look at the different ways of handling exceptions in python. We shall follow the example of ZeroDivisionError here and all other exceptions can be handled similarly.

Try-except block/statement in Python

In this example, we look at the usage of the try-except statement for exception handling.

If a programmer suspects that a particular piece of code could lead to an exception being raised, he/she can specify it in the try part of the try-except statement.

The corresponding exception can be mentioned in the except part of the statement.

Do keep in mind the required colon(:) and indentation.

Here, we have two variables a and b with values 2 and 0 respectively.

If we try to divide a by b, it would raise a ZeroDivisionError exception and we shall use the try-except statement to handle it.

Let us take a look at the python code and corresponding output for this method:

# Take two variables
a = 2
b = 0
# Add try block to enclose the suspect code
try:
  # It can raise an exception
  c=a/b 
# It is a handler; to handle the exception
except:
  print("An error or exception was encountered")

Output

An error or exception was encountered

Handle Specific Exception in Python

If we want to aim to handle specific exceptions with specific pieces of code to be executed if a particular exception is encountered, we specify the name of the exception in the except statement.

Let us take a look at the python code and corresponding output for this method:

# Take two variables
a = 2
b = 0

# Add try block to enclose the suspect code
try:
  # It can raise an exception
  c=a/b 
# It is a handler, to handle the exception
except ZeroDivisionError:
  print("You tried to divide by zero")

Output

You tried to divide by zero

Multiple Exceptions Handling in Python

If we want to handle multiple exceptions that could potentially arise from the code in a single try block, we use multiple except statements.

Let us take a look at the python code and corresponding output for this method:

# Take two variables
a = 2
b = 0
# Add try block to enclose the suspect code
try:
  # It can raise an exception
  c=a/d # changed the variable b to d to get a name error
# It is a handler; to handle the exception
except ZeroDivisionError:
    print("You tried to divide by zero")
except NameError:
    print("A name error was encountered")
  

Output

A name error was encountered

Print Default message of exceptions in Python

In python, the exceptions also have a default built-in message that can be displayed for each type of exception. For this, we follow a syntax as:

except <name_of_exception> as <variable_name>:

Here the exception is ZeroDivisionError and we use the temporary variable name as e, then we print it. Let us take a look at the python code and corresponding output for this method - 

# Take two variables
a = 2
b = 0
# Add try block to enclose the suspect code
try:
  # It can raise an exception
  c=a/b # changed the variable b to d to get name error
# It is a handler; to handle the exception
except ZeroDivisionError as e:
    print("An exception occured: ",e)
except NameError:
    print("A name error was encountered")

Output

An exception occured:  division by zero

Using the try-except-else statement in Python

There might arise a case when the exception is not encountered at all and if the user is notified of such a case as well, the exception handling method becomes more informative and helpful.

For this, we use the try-except-else statement. Try contains the piece of code that could potentially lead to exceptions, except contains the piece of code to be executed in case an exception is encountered and else contains the piece of code to be executed in case no exception is encountered.

Here, we have two variables a and b with values 2 and 1. If we divide a by b, it is a perfectly valid operation so no exception is raised and the piece of code in the else block is executed.

Let us look at the python code and corresponding output for this example:

# Take two variables
a = 2
b = 2 # changed it 0 to 2 for the else block
# Add try block to enclose the suspect code
try:
  # It can raise an exception
  c=a/b # changed the variable b to d to get name error
# It is a handler; to handle the exception
except ZeroDivisionError as e:
    print("An exception occured: ",e)
except NameError:
    print("A name error was encountered")
else:
    print("No error or exception was encountered")

Output

No error or exception was encountered

Using the finally statement/block in Python

There might arise a case when there is a piece of code you want to execute no matter if an exception is encountered or not.

For this, we use the finally statement. Any piece of code within this statement is always executed.

Here, we have two variables a and b with values 2 and 0. If we divide a by b, it results in a ZeroDivisionError so the piece of code in the except block is executed, after which the piece of code in the finally block is executed.

Let us look at the python code and corresponding output for this example:

# Take two variables
a = 2
b = 0
# Add try block to enclose the suspect code
try:
  # It can raise an exception
  c=a/b # changed the variable b to d to get name error
# It is a handler; to handle the exception
except ZeroDivisionError as e:
    print("An exception occured: ",e)
except NameError:
    print("A name error was encountered")
else:
    print("No error or exception was encountered")
finally:
    print("This block is always executed because it is finally block")

Output

An exception occured:  division by zero
This block is always executed because it is finally block

Conclusion

In this topic, we have learned the use and advantages of exception handling in a Python program, following some simple running examples, thus giving us an intuition of how this concept could be applied in real-world situations. Feel free to reach out to [email protected] in case of any suggestions.