1

Here is my code:

template<class T>
void Matrix<T>::set(const int i, const int j, const T v) {
    try {
        m[i][j] = v;
    } catch (std::exception& e) {
        std::cout << "Standard exception: " << e.what() << std::endl;
    }
}

But, I am on the safe side here? I mean, it is possible that i and/or j are out of bound, but the program receives on segmentation fault, will then an exception been thrown?

If this is not a good approach, then should I use assert() maybe?

gsamaras
  • 71,951
  • 46
  • 188
  • 305
  • "No" to all questions. "It depends" for the last one. – Ivan Aksamentov - Drop Oct 16 '15 at 22:54
  • OK @Drop, how would you do it? – gsamaras Oct 16 '15 at 22:55
  • Saying why you downvote would help! – gsamaras Oct 16 '15 at 23:14
  • 1
    @juanchopanza That wasn't the question....! – gsamaras Oct 16 '15 at 23:15
  • Maybe. But the answer is obviously no. – juanchopanza Oct 16 '15 at 23:17
  • @juanchopanza For a guy with a gold tag of c++, *of course* it is. For an average guy like me, that knows **nothing** about exceptions it is not! Did you downvote for that reason?! – gsamaras Oct 16 '15 at 23:18
  • No. It isn't that hard to search for this stuff. It has been answered a zillion times. – juanchopanza Oct 16 '15 at 23:20
  • A zillion times @juanchopanza in places you have seen, but when I asked the question, I first search all the auto-filled question SO gave me... Why was I downvoted then? Damn it, it's not fair. – gsamaras Oct 16 '15 at 23:23
  • 1
    I can re-open the question, no problem. The duplicate came from the "related" links, meaning it isn't hard to find. Don't worry too much about a single down-vote, there could be all kinds of reasons for that. – juanchopanza Oct 16 '15 at 23:25
  • No @juanchopanza, you are a superuser, I trust you. Thank you for taking the time to answer my comments! – gsamaras Oct 16 '15 at 23:26
  • 1
    @gsamaras Don't worry it happens sometimes. Arrays don't trow exceptions. Error handling in C++ is a complex opinionated topic (because C++ applications from embedded to mainframes are very different). I would recommend you to look at [famous book list](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and specifically Chapter II.13 of [Bjarne's book](http://www.amazon.com/The-Programming-Language-4th-Edition/dp/0321563840), so you could find out your own truth. – Ivan Aksamentov - Drop Oct 16 '15 at 23:26
  • 1
    Another good discussion of C++ error handling is in [Sutter, Alexandrescu -- Coding Standards](http://www.amazon.com/Coding-Standards-Rules-Guidelines-Practices/dp/0321113586). – Ivan Aksamentov - Drop Oct 16 '15 at 23:33
  • Thank you all for the comments. – gsamaras Oct 16 '15 at 23:35
  • This is one of the places where C and C++ line up well, excepting the exceptions of course. Correct use is not penalized with any sanity checking unless it is explicitly stated in the documentation. In the absence of documentation, assume unchecked. – user4581301 Oct 16 '15 at 23:35
  • You asked in the comments for where you can find the relevant information. Here is the site that I always use for this purpose: http://en.cppreference.com/w/cpp And more specifically to your question: http://en.cppreference.com/w/cpp/container/vector/operator_at As you see, it very clearly says that "no bounds checking is performed". As such, if `m` is an `std::vector<>`, you don't have the ghost of a chance to catch an out of bounds condition with your `try{} catch`. I have found the information at this site to be both very precise and very detailed. – cmaster - reinstate monica Oct 16 '15 at 23:47
  • @cmaster thank you. It is interesting to leave this here too then: http://www.cplusplus.com/reference/stdexcept/out_of_range/ – gsamaras Oct 16 '15 at 23:51

3 Answers3

6

Just add bounds checks.

C++ does not do bounds checking on arrays, let alone throw exceptions.

With vectors/std::array you can use the .at() method instead of [] operator to get checking.

Lastly, GSL introduces the array_view which lets you add "zero cost annotation" so that analysis tools can do the bounds checking. There is no de-facto standard implementation of GSL that has emerged yet. See also:

sehe
  • 374,641
  • 47
  • 450
  • 633
3

No.

Exception checking is maybe okay (but not at all elegant) when only reading from the array.

When writing, however, you risk overwriting "foreign" memory, that is a huge security risk, plus it might alter the execution flow by overwriting stack frames and who knows what - that is, there are certainly circumstances when the exception handler won't run even if it is actually expected to throw.

The best decision is to check indices on every iteration. Given that you mentioned asserting, I suppose you do know the array dimensions to start with.

3
template<class T>
void Matrix<T>::set(const int i, const int j, const T v) {
    try {
        m[i][j] = v;
    } catch (std::exception& e) {
        std::cout << "Standard exception: " << e.what() << std::endl;
    }
}

You don't mention what type m is, but assuming it's a custom type that does bounds checking in operator[], then you should be okay. The bounds check will (or should) happen, and an exception should be thrown, before any attempt at an out-of-bounds write.

But note that C++ doesn't do bounds checking itself on raw (C) arrays, and neither do any of the standard library types in their operator[] implementations, so if m is one of these types then you'll never get an exception thrown. Instead, STL types provide an at() method which you should use instead if bounds checking is desired.

Tristan Brindle
  • 16,281
  • 4
  • 39
  • 82