Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python | Raising an Exception to Another Exception
Next article icon

Test if a function throws an exception in Python

Last Updated : 20 Aug, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report

The unittest unit testing framework is used to validate that the code performs as designed. To achieve this, unittest supports some important methods in an object-oriented way:  

  • test fixture
  • test case
  • test suite
  • test runner

A deeper insight for the above terms can be gained from https://www.geeksforgeeks.org/unit-testing-python-unittest/

assertRaises() – It allows an exception to be encapsulated, meaning that the test can throw an exception without exiting the execution, as is normally the case for unhandled exceptions. The test passes if exception is raised, gives an error if another exception is raised, or fails if no exception is raised.

There are two ways you can use assertRaises:

  1. using keyword arguments.
    assertRaises(exception, function, *args, **keywords)  

    Just pass the exception, the callable function and the parameters of the callable function as keyword arguments that will elicit the exception.

  2. using context manager 
      assertRaises(exception)  

    Make a function call that should raise the exception with a context. The context manager will caught an exception and store it in the object in its exception attribute. This is useful when we have to perform additional checks on the exception raised.

We write a unittest that fails if no exception is raised by a function or when an exception raised by assert statement is different from expected exception. Thus, by this method we can check if an exception is raised by a function or not.

Example 1 :

Python3




import unittest
  
class MyTestCase(unittest.TestCase):
  
   # Returns true if 1 + '1' raises a TypeError
   def test_1(self):
      with self.assertRaises(Exception):
         1 + '1'
  
if __name__ == '__main__': 
    unittest.main()
 
 

Output : 

.  ----------------------------------------------------------------------  Ran 1 test in 0.000s    OK

Here, in the output the “.” on the first line of output means that test has passed and the function has thrown an exception of  TypeError while adding an integer value and a string value.

Example 2 :

Python3




import unittest
  
class MyTestCase(unittest.TestCase):
  
   # Returns false if 1 + 1 raises no Exception
   def test_1(self):
      with self.assertRaises(Exception):
         1 + 1
  
if __name__ == '__main__': 
    unittest.main()
 
 

Output : 

F  ======================================================================  FAIL: test_1 (__main__.MyTestCase)  ----------------------------------------------------------------------  Traceback (most recent call last):    File "/home/5bc65171e57a3294596f5333f4b7ed53.py", line 6, in test_1      1 + 1  AssertionError: Exception not raised    ----------------------------------------------------------------------  Ran 1 test in 0.001s    FAILED (failures=1)

Since adding an integer to an integer (in this case 1 + 1)  does not raise any exception, results in the unittest to fail.

Example 3 :

Python3




import unittest
  
class MyTestCase(unittest.TestCase):
  
  # Returns true if 100 / 0 raises an Exception
   def test_1(self):
      with self.assertRaises(ZeroDivisionError):
         100 / 0
  
if __name__ == '__main__': 
    unittest.main()
 
 

Output :

.  ----------------------------------------------------------------------  Ran 1 test in 0.000s    OK

Any number divided by 0 gives ZeroDivisionError exception. Therefore, in example 3, when 100 is divided by 0 it raises an Exception of type ZeroDivisionError resulting in unittest to pass. Thus “.” in output signifies that the test has been passed.

Example 4 :

Python3




import unittest
  
class MyTestCase(unittest.TestCase):
  
  # Returns true if GeeksforGeeks.txt file is not present and raises an EnvironmentError
  # Exception
  # In this example expected exception is RuntimeError while generated exception is
  # EnvironmentError, thus returns false
    def test_1(self):
        with self.assertRaises(RuntimeError):
            file = open("GeeksforGeeks.txt", 'r')
  
if __name__ == '__main__':
    unittest.main()
 
 

Output :

E  ======================================================================  ERROR: test_1 (__main__.MyTestCase)  ----------------------------------------------------------------------  Traceback (most recent call last):    File "/home/8520c06939bb0023b4f76f381b2c8cf2.py", line 11, in test_1      file = open("GeeksforGeeks.txt", 'r')  FileNotFoundError: [Errno 2] No such file or directory: 'GeeksforGeeks.txt'    ----------------------------------------------------------------------  Ran 1 test in 0.001s    FAILED (errors=1)

When we try to open a file that does not exists, it raises an IOError which is sub class of EnvironmentError. In the above example, the unittest failed because the type of exception to be raised by function was expected to be of type RuntimeError, instead it raised an exception of EnvironmentError. Since the exception raised and exception expected are different, it produces an error.



Next Article
Python | Raising an Exception to Another Exception

R

rohanchopra96
Improve
Article Tags :
  • Python
  • Python-exceptions
Practice Tags :
  • python

Similar Reads

  • How to Define and Call a Function in Python
    In Python, defining and calling functions is simple and may greatly improve the readability and reusability of our code. In this article, we will explore How we can define and call a function. Example: [GFGTABS] Python # Defining a function def fun(): print("Welcome to GFG") # calling a fu
    3 min read
  • Handling a thread's exception in the caller thread in Python
    Multithreading in Python can be achieved by using the threading library. For invoking a thread, the caller thread creates a thread object and calls the start method on it. Once the join method is called, that initiates its execution and executes the run method of the class object. For Exception hand
    3 min read
  • Python | Raising an Exception to Another Exception
    Let's consider a situation where we want to raise an exception in response to catching a different exception but want to include information about both exceptions in the traceback. To chain exceptions, use the raise from statement instead of a simple raise statement. This will give you information a
    2 min read
  • How to pass argument to an Exception in Python?
    There might arise a situation where there is a need for additional information from an exception raised by Python. Python has two types of exceptions namely, Built-In Exceptions and User-Defined Exceptions.Why use Argument in Exceptions? Using arguments for Exceptions in Python is useful for the fol
    2 min read
  • Handling TypeError Exception in Python
    TypeError is one among the several standard Python exceptions. TypeError is raised whenever an operation is performed on an incorrect/unsupported object type. For example, using the + (addition) operator on a string and an integer value will raise a TypeError. ExamplesThe general causes for TypeErro
    3 min read
  • How to Ignore an Exception and Proceed in Python
    There are a lot of times when in order to prototype fast, we need to ignore a few exceptions to get to the final result and then fix them later. In this article, we will see how we can ignore an exception in Python and proceed.  Demonstrate Exception in Python Before seeing the method to solve it, l
    3 min read
  • How to detect whether a Python variable is a function?
    There are times when we would like to check whether a Python variable is a function or not. This may not seem that much useful when the code is of thousand lines and you are not the writer of it one may easily stuck with the question of whether a variable is a function or not. We will be using the b
    3 min read
  • How to call a function in Python
    Python is an object-oriented language and it uses functions to reduce the repetition of the code. In this article, we will get to know what are parts, How to Create processes, and how to call them. In Python, there is a reserved keyword "def" which we use to define a function in Python, and after "d
    5 min read
  • Python unittest - assertIsNone() function
    assertIsNone() in Python is a unittest library function that is used in unit testing to check that input value is None or not. This function will take two parameters as input and return a boolean value depending upon assert condition. If input value is equal to None assertIsNone() will return true e
    2 min read
  • Python unittest - assertIsNone() function
    assertIsNone() in Python is a unittest library function that is used in unit testing to check that input value is None or not. This function will take two parameters as input and return a boolean value depending upon assert condition. If input value is equal to None assertIsNone() will return true e
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences