- In below mention code when I call "method" with - floatargument, it automatically cast to- intand perform the necessary task. But when if I throw- floattype and the immediate- catchexpects- intargument, it is not working? why?
- Another thing, if there is no - catchstatement with- floatthen should it go to general- catchand from there if I re-throw which- catchwill 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"; }
- 
                    Sorry my mistake, it is not float it is double. – ks2 Jan 30 '13 at 10:52
3 Answers
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:
- Implicit conversions won't work for exceptions. See: Can you catch an exception by the type of a conversion operator?
- Exceptions not caught will terminate your program.  So rethrowing it will cause a call to terminate(), and your program is dead.
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.
 
    
    - 70,775
- 16
- 139
- 220
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
 
     
     
     
    