user6737962
user6737962

Reputation:

Fail to catch exceptions in c++: failure to identify exception type

#include <iostream>
#include <exception>
#include <string>
using namespace std; 

int main()
{
    try {
        cout << "Please input your age: " << endl;
        int age;
        cin >> age;

        if (age > 100 || age < 0) {

            throw 130.1;
            throw 101;
        }
            cout << "Good input\n";

    }

    catch (char e) {
        cout << "Wrong input as char " <<e<< endl;
    }
    catch (int e) {
        cout << "Wrong input as int " <<e<< endl;
    }
    catch (float e) {
        cout << "Wrong input as double " <<e<< endl;
    }
    catch (...) {
        cout << "Wrong " << endl;
    }
}

Why when I enter 103.1 & 101, exceptions caught go to catch (...) instead of the respective catch(float e) & catch (int e).

Upvotes: 0

Views: 46

Answers (2)

songyuanyao
songyuanyao

Reputation: 172924

  1. 130.1 is a double literal,

suffix, if present, is one of f, F, l, or L. The suffix determines the type of the floating-point literal:

(no suffix) defines double
f F defines float
l L defines long double

You need to change catch (float e) to catch (double e).

  1. throw 101; is placed after throw 130.1, so it won't be executed at all, then impossible to enter catch (int e) block.

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234715

130.1 is a double literal, so you need a catch (double) for that one (if you want to throw a float then use throw 130.1f;).

Program control never reaches throw 101;, so catch (int) is redundant.

Upvotes: 2

Related Questions