• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Error Handling / Exception Handling in Python: Writing a Robust Python Program

Exception Handling in Python: Writing a Robust Python Program

Author: Aditya Raj
Last Updated: May 5, 2021

While writing programs in python, there may be situations where the program enters into an undesirable state called exceptions and exits the execution. This may cause loss of work done or may even cause  memory leak. In this  article, we will see how to handle those exceptions so that the program can continue executing in a normal way using exception handling in python. We will also see what are different ways to implement exception handling in python.

What are exceptions in Python?

An exception is an undesirable event/error in a program which disrupts the flow of execution of the statements in the program and stops the execution of the program if the exception is not handled by the program itself.  There are some predefined exceptions in python. We can also declare user defined exceptions by defining the exceptions by creating classes which inherit Exception class in python and then creating the exceptions using the raise keyword during the execution of the program.

In the following program, we create a dictionary and try to access the values using the keys in the python dictionary . Here, an error occurs in second print statement as "c" is not present in the dictionary as a key. The program will stop execution when an error is encountered.

#create a dictionary
myDict={"a":1,"b":2}
#this will print the value
print(myDict["a"])
#this will generate a KeyError exception and program will exit.
print(myDict["c"])

Output:

1
Traceback (most recent call last):
  File "<string>", line 6, in <module>
KeyError: 'c'

In the above code, we can see that after printing 1, program exits at second statement and notifies that KeyError has occurred. We can Handle this error and generate custom output using python try and except blocks.

How to handle exceptions in python?

To handle the exceptions that can be generated by the program, we use python try except and finally blocks in our code to execute the statements .

  • The try block has the code to be executed which may generate errors/exceptions.
  • The except block has the code to handle the errors/exceptions generated in the try block. 
  • The code in the finally block always executes, whether the try block has generated an exception or not, finally block will be executed.

We write our code which has to be executed in try block. In the except block, we write the code to handle the exceptions generated by try block. In the finally block, we implement those parts of code which has to be executed in the end. It doesn’t matter whether an exception is generated or not, finally block will always be executed after try and except block.

In the following code we implement the program used in previous example using try and except block so that program terminated normally when the error is encountered.

try:
    #create a dictionary
    myDict={"a":1,"b":2}
    #this will print the value
    print(myDict["a"])
    #this will generate a KeyError exception and program will exit from try  block
    print(myDict["c"])
except:
    print("Error Occurred in Program. Terminating.")

Output

1
Error Occurred in Program. Terminating.

In the above example, we can see that after executing first print statement in try block, the program does not terminate. After encountering error, it executes the statements in the except block and then terminates. Here we have to keep in mind that statements in the try block after the point at which exception occurred will not get executed.

How to handle specific exceptions in python?

To handle each exception differently, we can provide arguments to the exception blocks. When an exception is generated which is the same type that of the argument, the code in the specific block will be executed.

In the following code, we will handle KeyError exception specifically and rest of the exceptions will be handled by a normal except block.


try:
    #create a dictionary
    myDict={"a":1,"b":2}
    #this will print the value
    print(myDict["a"])
    #this will generate a NameError exception and program will exit from try block
    print(a)
except(KeyError):
    print("Key is not present in the dictionary. proceeding ahead")
except: 
    print("Error occured. proceeding ahead")
try:
    #create a dictionary
    myDict={"a":1,"b":2}
    #this will print the value
    print(myDict["a"])
    #this will generate a NameError exception and program will exit from try block
    print(myDict["c"])
except(KeyError):
    print("Key is not present in the dictionary. Terminating the program")
except: 
    print("Error occured. Terminating")

Output:

1
Error occured. proceeding ahead
1
Key is not present in the dictionary. Terminating the program

In the above program, we can see that KeyError has been handled specifically by passing it to an except block as a parameter and other exceptions are handled normally during exception handling in python .

When to use Finally block in exception handling in Python? 

Finally block is used when some statements in the program need to be executed  whether or not an exception is generated in the program. In programs where file handling is done or network connections are used, It is necessary that the program should terminate the connections or close the file before terminating. We put the finally block after the try and except block.

try:
    #create a dictionary
    myDict={"a":1,"b":2}
    #this will print the value
    print(myDict["a"])
    #this will generate a NameError exception and program will exit from try block
    print(myDict["c"])
except(KeyError):
    print("Key is not present in the dictionary. proceeding ahead")
finally:
    print("This is the compulsory part kept in finally block and will always be executed.")

Output:

1
Key is not present in the dictionary. proceeding ahead
This is the compulsory part kept in finally block and will always be executed.

In the above code, we can see that the try block has raised an exception, the exception has been handled by the except block and then the finally block is executed at last.

When to use else block in exception handling in Python?

We can also use else block with python try except block when we need to execute certain statements of code after the successful execution of the statements in the try block. Else block is written after try and except block. Here, we have to keep in mind that errors/exceptions generated in the else block are not handled by the statements in the except block.


try:
    #create a dictionary
    myDict={"a":1,"b":2}
    #this will print the value
    print(myDict["a"])
except:
    print("I am in except block and will get executed when an exception occurs in try block")
else:
    print("I am in else block and will get executed every time after try block is executed successfully.")

Output:

1
I am in else block and will get executed every time after try block is executed successfully.

In the above program, we can see that the code in else block has executed when try block has executed successfully. If try block raises an exception then only the except block will get executed. If the try block generates an exception then the code in the else block will not be executed.

How to generate user defined exceptions in Python?

We can also put constraints on some values by using exception handling in python. To generate a user defined exception, we use the “raise” keyword when a certain condition is met. The exception is then handled by the except block of the code.

To create a user defined exception, we create a class with desired exception name which should inherit Exception class. After that, we can raise the exception in our code anywhere according to our need to implement constraints.

#create an exception class
class SmallNumberException (Exception):
    pass

try:
    #create a dictionary
    myDict={"a":1,"b":2}
    #this will raise SmallNumberException
    if(myDict["a"]<10):
        raise SmallNumberException
except(SmallNumberException):
    print("The Number is smaller than 10")

Output:

The Number is smaller than 10

In the above code, we can see that a user defined exception has been created which inherits Exception class and is raised after a conditional statement to check whether the number is smaller than 10 or not. We can use user defined exceptions anywhere to add constraints on values of a variable in the program.

Conclusion

In this article, we have learned about exceptions and exception handling in python. We also studied how to implement try, except ,finally and else block during exception handling. Also, we have studied how to create custom user defined errors and exceptions to implement constraints on the variables.

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

Filed Under: Error Handling Tagged With: exception handling, try except Author: Aditya Raj

More Python Topics

API Argv Basics Beautiful Soup bitly Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary – How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehensions in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Pandas Append Row to DataFrame
  • Convert String to DataFrame in Python
  • Pandas DataFrame to List in Python
  • Solved: Dataframe Constructor Not Properly Called Error in Pandas
  • Overwrite a File in Python

Copyright © 2012–2023 · PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us