---
title: "How to test functions that throw exceptions?"  
description: "How to test functions that throw exceptions?"  
author: "Revati S Misra"  
published: 2023-07-20  
updated: 2023-07-20  
canonical: https://www.mindstick.com/forum/159177/how-to-test-functions-that-throw-exceptions  
category: "exception handling"  
tags: ["exception handling", "exception"]  
reading_time: 2 minutes  

---

# How to test functions that throw exceptions?

How to [test](https://yourviews.mindstick.com/story/1427/explosive-facts-about-trinity-test-world-s-first-nuclear-bomb) [functions](https://www.mindstick.com/forum/160140/explain-the-role-of-functions-as-a-service-faas-in-serverless-computing) that throw [exceptions](https://www.mindstick.com/interview/22871/define-predifined-generic-exceptions)

## Replies

### Reply by Aryan Kumar

To test functions that throw exceptions, you can use the following steps:

1. Create a test case class for the function you want to test.
2. In the test case class, create a test method for each exception that the function can throw.
3. In each test method, call the function and assert that it throws the expected exception.

For example, the following code shows how to test a function that throws an `ArithmeticException` if the denominator of a division operation is zero:

Java

```plaintext
import org.junit.Test;

public class MyFunctionTest {

  @Test
  public void testDivisionByZero() {
    // Arrange
    int numerator = 10;
    int denominator = 0;

    // Act
    try {
      myFunction(numerator, denominator);
    } catch (ArithmeticException e) {
      // Assert
      assertTrue(e.getMessage().contains("Division by zero"));
    }
  }

  private void myFunction(int numerator, int denominator) {
    if (denominator == 0) {
      throw new ArithmeticException("Division by zero");
    }
  }
}
```

In this code, the `testDivisionByZero()` method first sets up the test by creating two variables, `numerator` and `denominator`. `numerator` is set to 10 and `denominator` is set to 0. The method then calls the `myFunction()` function, which is the function that is being tested. The `myFunction()` function throws an `ArithmeticException` if the denominator is zero. The `testDivisionByZero()` method catches the `ArithmeticException` and asserts that the message of the exception contains the string "Division by zero".

This is just one example of how you can test functions that throw exceptions. There are many other ways to do this, and the best way will depend on the specific function that you are testing.


---

Original Source: https://www.mindstick.com/forum/159177/how-to-test-functions-that-throw-exceptions

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
