2
  • In below mention code when I call "method" with float argument, it automatically cast to int and perform the necessary task. But when if I throw float type and the immediate catch expects int argument, it is not working? why?

  • Another thing, if there is no catch statement with float then should it go to general catch and from there if I re-throw which catch will handle it?

    int method(int i)
    {
        return i--;
    }
    void main()
    {
        try {
            cout<<method(3.14);
            throw string("4");
        }
        catch(string& s){
            try{
                cout << s;
                throw 2.2;
            }
            catch(int i)
                cout<<i;
    
            catch(...)
                throw;
    
            cout<<"s"+s;
        }
        catch(...)
            cout<<"all";
    }
    
minopret
  • 4,726
  • 21
  • 34
ks2
  • 43
  • 1
  • 8

3 Answers3

2

Please do not use exceptions like this. Exceptions are for exceptional circumstances, not normal program logic. Every time exceptions are abused, $DEITY kills a kitten. By throwing it. Into a pit. Of fire. And sadness.


That being said:

Community
  • 1
  • 1
sheu
  • 5,653
  • 17
  • 32
2

The function call is resolved at compile time, where the compiler is able to check the types, find the closest match (overload resolution) and then do the appropriate conversion. No such things happen in runtime when an exception is propagated. The exception is caught by a catch that matches the type exactly, or one of the exception's unambiguous bases. In your case int simply does not match a double.

As with your second problem: your rethrow is not enclosed by a try block, so it is not caught by the last catch(...). The last catch(...) corresponds to the first try block.

Yakov Galka
  • 70,775
  • 16
  • 139
  • 220
1

Simple variables can be converted into other simple types in several cases. One of them is if such a conversion is necessary to call a method. That is what is happening in your case 1 -- and it is happening during the compilation, the call is not resolved during runtime. If you want to forbid such behavior, use explicit keyword

However, if there are two methods with different types of arguments, the method which argument is "the closest" to the argument you pass will be chosen. The type conversion does not apply to throw. It will match only if the type thrown matches the type in the argument of catch. Hence the default catch working.

BTW: you are actually using double values, not floats! 2.2f would be a float

Community
  • 1
  • 1
Dariusz
  • 21,561
  • 9
  • 74
  • 114