Prime numbers

Hi,

I`m getting error when trying to compile

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
  #include <iostream>
#include <vector>

using namespace std;

vector<int>prime;

bool is_prime(int n)
{
	for (int p = 0; p<prime.size(); ++p)
	
      {
	
        if (n%prime[p]==0) return false;	// no remainder: prime[p] divided
	
         return true;	// no smaller prime could divide

      }
}

int main()

{


   try
  {
	prime.push_back(2);	// consider the smallest prime

	for (int i = 3; i<=100; ++i)	// test all integers [3:100]
		if (is_prime(i)) { prime.push_back(i); }	// add new prime to vector

	cout << "Primes: ";
	for (int p = 0; p<prime.size(); ++p)
	      {  cout << prime[p] << '\n'; }

  }


}



Error messages:

1
2
3
4
5
6
7
8
9
10

Documents/Program25.cpp: In function ‘int main()’:
Documents/Program25.cpp:40:1: error: expected ‘catch’ before ‘}’ token
 }
 ^
Documents/Program25.cpp:40:1: error: expected ‘(’ before ‘}’ token
Documents/Program25.cpp:40:1: error: expected type-specifier before ‘}’ token
Documents/Program25.cpp:40:1: error: expected ‘)’ before ‘}’ token
Documents/Program25.cpp:40:1: error: expected ‘{’ before ‘}’ token



I couldn`t understand them no matter what.
expected ‘catch’

If those words do not ring any bell, then perhaps a simpler program could help to focus on the issue:
1
2
3
4
5
int main() {
  try
  {
  }
}

In other words, that try-block is not syntactically complete.
See http://en.cppreference.com/w/cpp/language/try_catch
Replacing "int" with "size_t" seems to get rid of the other errors so that leaves "catch" left.

for (size_t p = 0; p < prime.size(); ++p)
what would you expect if you write try without catch
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

#include <iostream>
#include <vector>


using namespace std;

{

vector<int> prime;


bool is_prime(int n)
{
	for (int p = 0; p<prime.size(); ++p)
		if (n%prime[p]==0) return false;	// no remainder: prime[p] divided
	return true;	// no smaller prime could divide
}
int main()
try
{
	prime.push_back(2);	// consider the smallest prime

	for (int i = 3; i<=100; ++i)	// test all integers [3:100]
		if (is_prime(i)) prime.push_back(i);	// add new prime to vector

	cout << "Primes: ";
	for (int p = 0; p<prime.size(); ++p)
		cout << prime[p] << '\n';

	
}
catch (runtime_error e) {	
	cout << e.what() << '\n';
	
}
catch (...) {	
	cout << "exiting\n";
	
 }


}
Topic archived. No new replies allowed.