Testing That No Exception Is Thrown in Java

Last Updated : 23 Jul, 2025

An exception is an interruption that may occur during the execution(Runtime) of the program. Testing that no Exception is thrown in is all about error-free code and its stable smooth running. Each time an exception occurs, program execution fails. An error message is displayed on the screen. When do exceptions occur in programs?

Generally, these errors occur when :

  1. The user provides some invalid input
  2. Some files that were needed in the code are missing in the folder or don't exist at all
  3. Programs run out of available memory space

Importance of Ensuring No Exception Is Thrown

It is important to keep in mind that exceptions are just errors but these errors when handled correctly do not allow the program to crash and just return an alert to the user that something wrong has happened with the program. Taking this on large-scale industry-deployable code becomes critical because this prevents a large code database from crashing and getting wrecked. It protects data integrity, enhances security, improves maintainability, and helps meet performance, legal, and business requirements. By managing potential exceptions, developers can build robust software that delivers a smooth and dependable experience for users.

How to verify that No Exception is thrown in your code?

JUnit is a Java framework that is popular nowadays and helps users verify that no exception is thrown in the code. JUnit 5 provides an easy way to perform this check. We perform a JUnit test that checks if a specific part of your code works as expected.

First, make a separate folder for this project(eg. TestExceptions). Then follow the below steps to run the Junit framework in Java:

  1. Make a sub-folder named 'lib'
  2. Download the necessary Jar files for : JUnit Platform Console Standalone and Hamcrest Core.

The required Jar files can be downloaded from any online Maven download tool. Use the XML code on the website.

1. For JUnit Platform Console Standalone » 1.11.0

XML
<!-- https://mvnrepository.com/artifact/org.junit.platform/junit-platform-console-standalone -->
<dependency>
    <groupId>org.junit.platform</groupId>
    <artifactId>junit-platform-console-standalone</artifactId>
    <version>1.11.0</version>
    <scope>test</scope>
</dependency>

2. For Hamcrest Core » 1.3

XML
<!-- https://mvnrepository.com/artifact/org.hamcrest/hamcrest-core -->
<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest-core</artifactId>
    <version>1.3</version>
    <scope>test</scope>
</dependency>

After the Zip folders have been downloaded, extract them to the lib folder we made earlier in our main Project Folder.

Next make a Java file named ExampleTest.java and use the code given below. I have written different test-cases to check for exceptions in the program each explained with a comment.

Java
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;

import org.junit.jupiter.api.Test;

public class ExampleTest {

    // Test to ensure no exception is thrown for a valid integer string
    @Test
    void givenValidIntegerString_whenParsed_thenNoExceptionThrown() {
        assertDoesNotThrow(() -> {
            Integer.parseInt("100");
        });
    }

    // Test to ensure an exception is thrown for an invalid integer string
    @Test
    void givenInvalidIntegerString_whenParsed_thenNumberFormatExceptionThrown() {
        assertThrows(NumberFormatException.class, () -> {
            Integer.parseInt("invalid");
        });
    }

    // Test to ensure no exception is thrown for a negative integer string
    @Test
    void givenNegativeIntegerString_whenParsed_thenNoExceptionThrown() {
        assertDoesNotThrow(() -> {
            Integer.parseInt("-100");
        });
    }

    // Test to ensure no exception is thrown for the largest valid integer string
    @Test
    void givenMaxIntegerString_whenParsed_thenNoExceptionThrown() {
        assertDoesNotThrow(() -> {
            Integer.parseInt(String.valueOf(Integer.MAX_VALUE));
        });
    }

    // Test to ensure no exception is thrown for the smallest valid integer string
    @Test
    void givenMinIntegerString_whenParsed_thenNoExceptionThrown() {
        assertDoesNotThrow(() -> {
            Integer.parseInt(String.valueOf(Integer.MIN_VALUE));
        });
    }

    // Test to ensure an exception is thrown for a string with leading spaces
    @Test
    void givenStringWithLeadingSpaces_whenParsed_thenNumberFormatExceptionThrown() {
        assertThrows(NumberFormatException.class, () -> {
            Integer.parseInt(" 123");
        });
    }

    // Test to ensure an exception is thrown for a string with trailing spaces
    @Test
    void givenStringWithTrailingSpaces_whenParsed_thenNumberFormatExceptionThrown() {
        assertThrows(NumberFormatException.class, () -> {
            Integer.parseInt("123 ");
        });
    }
}
  • After saving the Java file. Open a new terminal. Make sure the present working directory is same as the project folder.
  • Use the command : javac -cp ".;lib/junit-platform-console-standalone-1.11.0.jar;lib/hamcrest-core-1.3.jar" ExampleTest.java for the compiling your code
  • Next, Use the command : java -jar lib/junit-platform-console-standalone-1.11.0.jar --classpath ".;lib/hamcrest-core-1.3.jar" --scan-classpath for executing the code.
Screenshot-2024-08-18-193319-min
Output for exception test-cases

Explaining each test case:

  • givenValidIntegerString_whenParsed_thenNoExceptionThrown : The purpose of the test is to show that a valid string representation of an integer—that is, "100"—will be parsed correctly into the equivalent integer under the Integer.parseInt method without throwing any kind of exception. This will be the base test for checking that Integer.parseInt actually does the right thing with a valid input. Preventing unnecessary crashes or issues of an application by ensuring that it does not throw an exception for valid inputs is very important.
  • givenInvalidIntegerString_whenParsed_thenNumberFormatExceptionThrown : The string "invalid" which cannot be converted to an integer is passed to Integer.parseInt and should raise a NumberFormatException. This verifies that the Integer.parseInt method behaves correctly for invalid input by throwing the appropriate exception. This is important for any application that needs to handle errors appropriately.
  • givenNegativeIntegerString_whenParsed_thenNoExceptionThrown : he test checks that a valid string representation of a negative integer ("-100") is parsed correctly, without throwing any exceptions. Negative integers are valid inputs for the Integer.parseInt method, so it is crucial to make sure that the method indeed can correctly handle them, without raising any exceptions.
  • givenMaxIntegerString_whenParsed_thenNoExceptionThrown : The test that the string representation of the largest value an int can take which is Integer that is 2147483647, is parsed correctly without throwing any exception. Parsing of the maximum integer value is a boundary case. This test ensures that the upper limit of integer values is dealt with appropriately by the method.
  • givenMinIntegerString_whenParsed_thenNoExceptionThrown : The test checks if the string of the smallest possible int value, Integer. MIN_VALUE (-2147483648), is properly parsed and doesn't throw exceptions. As with the prior test, this is yet another edge case, but this time for the lower limit of the range of integer values. This test case guarantees that the method can properly handle the smallest possible integer.
  • givenStringWithLeadingSpaces_whenParsed_thenNumberFormatExceptionThrown : This test confirms that if a string with leading spaces, for example, " 123", is provided to Integer.parseInt, then the NumberFormatException will be thrown. This test assures that the method detects correctly and rejects string that is not purely numeric, including generally considered leading whitespace in invalid input.
  • givenStringWithTrailingSpaces_whenParsed_thenNumberFormatExceptionThrown: This test will ensure that a Number Format Exception is thrown when a string with leading and trailing spaces, like "123 ", is passed to Integer.parseInt(). Similar to the above test, this test will ensure that the method is not allowing strings with trailing whitespace to be parsed as an integer, which is very critical.

Common Pitfalls and How to Avoid Them:

Developers generally ignore certain cases when considering exception handling. They write robust, large-scale applications in Java necessitates exception handling.

Very common mistakes in handling exceptions include swallowing, catching too general exceptions, abusing checked exceptions, and, finally, not cleaning up resources. Tests should contain assertions guaranteeing expected behavior. Messages of exceptions shall not be used; exceptions are to be logged for better debugging . In multithreading environments, developers have to handle `InterruptedException` with care to avoid problems. By avoiding these pitfalls, you'll be able to produce cleaner, more reliable code that behaves in a predictable manner under error conditions.

Conclusion

In conclusion, ensuring that exceptions are correctly handled in your code is vital for creating robust, stable, and user-friendly applications. Proper exception handling prevents program crashes, protects data integrity, enhances security, and maintains code performance. Utilizing tools like JUnit for testing ensures that your code can gracefully handle various scenarios, including invalid inputs and edge cases. By avoiding common pitfalls in exception handling, developers can produce more reliable and maintainable software, providing a smooth and dependable experience for users.

Comment

Explore