How to check for zero and negative values? What to do with "std::domain_error"?

FAILED
Test 5
zero_is_an_error

TEST FAILURE

FAILED: REQUIRE_THROWS_AS( collatz_conjecture::steps(0), std::domain_error ) at /tmp/collatz-conjecture/collatz_conjecture_test.cpp:30

3 Likes

Hi @ArtyomCoder, welcome to the Exercism Forum and thank you for posting! My name is Jonathan and I’m the Community Manager - great to have you here.

If you could help us out by fleshing out the issue you are having with more detail that would be great. For example, is there a screenshot of your code? What was the issue specifically? What were you trying to do etc?

Currently it is a little tricky to understand what you need help with :slight_smile:

Thanks!

Look at the last two tests:

TEST_CASE("zero_is_an_error")
{
    REQUIRE_THROWS_AS(collatz_conjecture::steps(0), std::domain_error);
}

TEST_CASE("negative_value_is_an_error")
{
    REQUIRE_THROWS_AS(collatz_conjecture::steps(-15), std::domain_error);
}

They expect the function to throw an exception (specifically std::domain_error) if the parameter is non-positive.
For more about exceptions you might want to read Chapter 20: Exceptions at LearnCpp.com.

1 Like

@ArtyomCoder Were you able to solve your problem? Let us know if you need help. Cheers!

1 Like

Hi there.

In this exercise they expect your function to throw an exception of type std::domain_error when the provided number is less than or equal to zero.

The std::domain_error class is defined in the <stdexcept> header, therefore you’ll have to include it at the top of your code:

#include <stdexcept>

To know more about std::domain_error, you can check the following article:
https://en.cppreference.com/w/cpp/error/domain_error

Basically, to use this kind of exception you need to pass it a string (an empty string will do):

std::domain_error("")

If you’re not familiar with exceptions you can read the following articles:
https://www.learncpp.com/cpp-tutorial/the-need-for-exceptions/
https://www.learncpp.com/cpp-tutorial/basic-exception-handling/

But essentially you need to use a throw statement in your code, when some condition is met:

if ( n <= 0 ) {
    throw std::domain_error("");
}

I hope this helps.

Best regards.