Advertisement

Error handling

Started by January 20, 2025 03:01 AM
14 comments, last by frob 6 hours, 12 minutes ago

Is there a way to break a program without placing break points? I want the program to break if an array index is out of bounds. I can compare the index to the size of the array but what do I do if there is a mismatch?

My project`s facebook page is “DreamLand Page”

If you literally just want to trigger a breakpoint programmatically, there are APIs, depending on the OS (for example DebugBreak on Windows). Is that what you want to do, or do you want to implement some different form of error-handling? Another quick way of halting the application for debuggin is using assert, but if you want to do more advanced error-handling, this is a much more broad topic with multiple ways.

Advertisement

I think this technique is called "assertion" and it's a useful debugging tool. In JS/TS, you can use the console.assert() method or create a custom assertion function:-

function assertInBounds(array, index) {
  if (index < 0 || index >= array.length) {
    throw new Error(`Array index out of bounds: ${index} is not valid for array of length ${array.length}`);
  }
}

function getElementSafely(array, index) {
  assertInBounds(array, index);
  return array[index];
}

// example...
const myArray = [1, 2, 3, 4, 5];

console.log("Accessing valid index:");
console.log(getElementSafely(myArray, 2)); // this will work fine

console.log("\nTrying to access out of bounds index:");
try {
  getElementSafely(myArray, 10); // this will throw an error
} catch (error) {
  console.error(error.message);
}

console.log("\nProgram continues after catching the error");

Is this something you're looking to get solution?

Calin said:
I want the program to break if an array index is out of bounds.

If you use std::array, which has the same performance as the usual C array, you get out of bounds checks and a debug break in debug mode. Same behavior as with std::vector.
(iirc)

Is that what you want to do, or do you want to implement some different form of error-handling?

std Vector breaks when the index is out of bounds and it's not a break point, how is it done?

If you use std::array

I want to use my own thing )))

Juliean said:
there are APIs, depending on the OS

API sounds rather elaborate. I was hoping for something lite and easy to implement, something where you could include the library and then add two or three lines where it is needed.

My project`s facebook page is “DreamLand Page”

Calin said:
API sounds rather elaborate. I was hoping for something lite and easy to implement, something where you could include the library and then add two or three lines where it is needed.

That's an API, provided by the library that you already have included on that OS. Did you even check the link I provided? Its a single function you call where you need it. Same with assert, you call

assert(index < size);

And thats it.

Calin said:
std Vector breaks when the index is out of bounds and it's not a break point, how is it done?

Ok, so you do want actual error-handling. In this case, the easiest way is to use std::vector::at() instead of operator[], when you are not sure the index is in range. “at” has well-definde behaviour for out-ouf bounds indices. “at” throws an exception if the index is outside, which, if not caught, will act as a breakpoint, but can also be handled:

std::vector<int> v{0, 1, 2};

v[3]; // undefined
v.at(3); // throws => unhandled causes break-point like behaviour with a debugger attached

try
{
    v.at(3);
} // handle gracefully => log, fix, whatever
catch (std::out_of_range&) {}

Calin said:
I want to use my own thing )))

Well are you using std::vector or your own thing? That's really confusing now, because if you use std::vector you can/should also use std::array. If you want to use your own thing, don't use either.

Advertisement

JoeJ said:
If you use std::array, which has the same performance as the usual C array, you get out of bounds checks and a debug break in debug mode. Same behavior as with std::vector.

As mentioned above, the behaviour of operator[] with out-of-bounds indices for std::vector and array is undefined. So there is no guarantee those do any kinds of bound-checks, no matter what type of build. at() does those checks, but in all configurations, so there is a performance overhead - which should not matter for most cases, and in those that do, one can easily fallback to [] if having an in-bounds index is guaranteed.

Juliean said:
Well are you using std::vector or your own thing?

Thanks for your feedback Juliean. I'm using both but I'm relying on C arrays for heavy things.

My project`s facebook page is “DreamLand Page”

Calin said:
Thanks for your feedback Juliean. I'm using both but I'm relying on C arrays for heavy things.

Which is silly, because in this regard JoeJ was right - std::array, if using [] for access, is exactly the same as using a raw C-array in terms of performance, with additional benefits. From the cppreference:

The struct combines the performance and accessibility of a C-style array with the benefits of a standard container, such as knowing its own size, supporting assignment, random access iterators, etc.

There is never a reason to use a C-style array, really, ever. If you need to do pointer-math, just use a pointer. For storing or passing an fixed size array, always std::array. Do yourself a favour today and stop being randomly picky about stuff like this, and just use the better alternative, which is just one <array> header away ^.^

Juliean said:
As mentioned above, the behaviour of operator[] with out-of-bounds indices for std::vector and array is undefined. So there is no guarantee those do any kinds of bound-checks, no matter what type of build.

There is no guarantee on STL specs, but using MSVC with default STL we get the following behavior in debug mode:

		std::vector<int> test(5);
		test[5] = 1; // assert: vector subscript out of range
		
		std::array<int, 5> test2;
		test2[5] = 1; // assert: array subscript out of range
		
		int array[5];
		//array[5] = 1; // compile time error detected, but if the index was computed, memory corruption would go unnoticed

That's what he wants, i guess.

Advertisement