Try/Catch function

Can anybody explain to me what this is, and how it works in a simple way?
That's too much to read. I asked here so someone can explain it in a simpler way to me and show a simple example.
Then read the first part, up to "Exception specifications".
Alright.
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
#include <iostream>

using namespace std;

bool isPrime(int n) {
  if( n <= 1 )
    throw n; //throw exception (type int)

  for( int i = n - 1; i > 1; i-- )
    if( n % i == 0 )
      return false;
  return true;
}

void printIsPrime(int n) {
  cout << "Is " << n << " prime: " << (isPrime(n) ? "yes" : "no") << endl;
}

int main() {
  int a = 5,
    b = 10,
    c = -1,
    d = 2;

  try {
    printIsPrime(a);
    printIsPrime(b);
    printIsPrime(c); //try to jump to the catch block of the appropriate type
    printIsPrime(d);
  } catch(int num) {
    //int exceptions thrown in the above try block will be handled here
    cerr << "isPrime failed on " << num << endl;
  }
  
  return 0;
}
Topic archived. No new replies allowed.