Number getting too large

Lets say I had a simple program to iterate an integer.

Could I use an exception to stop the loop?

I tried this but it seems to loop forever. It seems numbers reset back to 0 when they reach their max value.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <exception>

int main () {
  short int number = 0; // should only go up to 32767
  int A = 0;

  do {
  try
  {
     number++;
  }
  catch (const std::exception &e)
  {
    std::cout << "Standard exception: " << e.what() << "\n";
    A = 1;
  }
  if (number == 32767) {
    std::cout << "At 32767 \n";
  }
  } while (A == 0);
  return 0;
}
> Could I use an exception to stop the loop?
Yes, but that is not the purpose of exceptions.

> It seems numbers reset back to 0 when they reach their max value.
¿who told you that that operations throws an exception?
It seems numbers reset back to 0 when they reach their max value.


it won't be zero in your case, it'll be –32,768.

And i agree with ne555, even if it worked like you thought it would (which it does not), using exceptions in this way would be mental.
Nobody. I'm just trying things until I understand how they work.

I'm not taking a class on this so the only way to figure out what is wrong with my bad ideas is to post them here.

I saw this on the exceptions page as a type of exception "operator="

I figured maybe since N++ is the same as N = N + 1 it would do something.


What is the purpose of exception again?

I assumed it acted sort of like an If (something) {}

except that it was for when something unexpected happened so you could tell the program to do something else. Maybe exiting a loop is bad form but I don't know much about this stuff yet.

It is likely I have the wrong idea of when to use an exception and how.
Last edited on
Topic archived. No new replies allowed.