Strange run order with system call

I was just playing around with exceptions the other day, when I came upon a very strange occurrence.

I ran this program:
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

void fn() {
  throw 12;
}

int main() {
  std::cout << "Hello World!\n";
  try { fn(); }
  catch(int e) { std::cout << e; }
  system("./pause");
  return 0;
}



Expecting output to be:
Hello World!
12Press Enter to continue




But instead I received:
Hello World!
Press Enter to continue

12


So I was confused of course and guessed that exception handlers just run after everything else, but that definitely didn’t seem right, so I changed the program slightly to be
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

void fn() {
  throw 12;
}

int main() {
  try { fn(); }
  catch(int e) { std::cout << e; }
  system("./pause");
  std::cout << "aaa";
  return 0;
}


And received

Hello World!
Press Enter to continue

12aaa


And now I’m just really confused. Why is my system call running before my handler???


also, pause is the compiled result of
1
2
3
4
5
#include <iostream>
int main() {
  std::cout << "Press Enter to continue" << std::endl;
  std::cin.ignore(1000,'\n');
}
Last edited on
Ah nvm I figured it out, it’s because pause flushed it’s output and main didn’t
Hello highwayman,

Looking at the code differently:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
include <iostream>

void fn()
{
	throw 12;
}

int main()
{
	try
	{
		fn();
	}
	catch (int e)
	{
		std::cout << e;
	}

	std::cout << "\n  Press Enter to continue: ";
	std::cin.ignore(1000, '\n');

	std::cout << " aaa";

	return 0;
}

It does exactly what you told it to,

I think what you want is:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>

void fn()
{
	throw 12;
}

int main()
{
	try
	{
		fn();
	}
	catch (int e)
	{
		std::cout << e;
	}

	std::cout << " aaa";  // <--- Moved. Added a space.

	std::cout << "\n\n  Press Enter to continue: ";
	std::cin.ignore(1000, '\n');

	return 0;
}

Line 16 may or may not flush the buffer until you reach line 22. The "cin" will flush the buffer before input is accepted.

Andy
Topic archived. No new replies allowed.