1

Hi guys so i have this constructor

Matrix::Matrix(size_t row, size_t col)
{
  if(row < 1 || col < 1)
    throw new std::runtime_error("Minimalni velikost matice je 1x1");
  matrix = std::vector<std::vector< double > >(row,std::vector<double>(col, 0));
}

and this test

Matrix *TestedMatrix;
EXPECT_THROW(TestedMatrix = new Matrix(-2,3),std::runtime_error );

but im still getting that exepction is of different type. I also tried std::runtime_error* but result is the same. I wanted use EXPECT_ANY_THROW at first but it was not displayed in my code coverage. Thanks for help ! :)

273K
  • 29,503
  • 10
  • 41
  • 64
Crky
  • 13
  • 1
  • 1
  • 4

2 Answers2

4

Don't call new.

Matrix::Matrix(size_t row, size_t col)
{
  if(row < 1 || col < 1)
    throw std::runtime_error("Minimalni velikost matice je 1x1");
  matrix = std::vector<std::vector< double > >(row,std::vector<double>(col, 0));
}

new is going to return a void* which is why you are getting the "exception is of different type" error.

Trevor Hickey
  • 36,288
  • 32
  • 162
  • 271
  • Yea thank you for your response. The problem is I cant change the code. Im just doing tests so do you have any idea how to solve this with calling new ? – Crky Feb 23 '17 at 07:50
  • Can you try `EXPECT_THROW(TestedMatrix = new Matrix(-2,3),void*);`? – Trevor Hickey Feb 23 '17 at 08:43
  • No, its not working. Alsa can I ask you if its better to use Matrix *TestedMatrix or Matrix Tested Matrix. Whats better about testing with pointer or vise versa . Thanks. – Crky Feb 23 '17 at 09:07
1

Assuming that size_t is an alias for std::size_t, you're seeing signed-to-unsigned conversion here (and your compiler should be warning you about that; check that you've enabled sufficient warnings in your build).

-2 gets converted to a very large positive value (very nearly SIZE_MAX), so the likelihood is that the constructor is throwing std::bad_alloc.

You need to pass 0 to the constructor to exercise the code path that throws std::runtime_error*. (And you can simplify the check to if (!row || !col), since 0 is the only unsigned value less than 1).

EXPECT_THROW(Matrix(0,3), std::runtime_error*);
EXPECT_THROW(Matrix(3,0), std::runtime_error*);

As an aside, I recommend that you throw by value rather than using new.

Toby Speight
  • 27,591
  • 48
  • 66
  • 103