"Firstly, how does the compiler know which catch() body to use if the there are multiple catch() with the same argument."
That would be ambiguous. Which one would it use? For a compiler to decide which handler to use, the handler must differ from the other handlers. The compiler will evaluate the type that was thrown, and will determine which handler best fits the thrown type.
Neil010 wrote:
(number1[i] != ".")
Of what type is number1? I'm assuming and integral value, since double-quoted strings are pointers.
So in this how would the compiler know which handler to use?
And, I was able to find the error in my code, thanks to you. I was comparing a character with a pointer. Hence, when I used single quotes instead of double quotes, my code worked fine.
I would expect it uses the first innermost catch block that it encounters. So in the case you gave, if you throw a const char* it will always be caught by the err block, and the err2 will never be used.
I would expect it uses the first innermost catch block that it encounters. So in the case you gave, if you throw a const char* it will always be caught by the err block, and the err2 will never be used.
That is exactly what I mean. Is there any other way in which you could use the other handler?
No. Exceptions are only thrown/caught by type. If you need to have the same exception do multiple things then you might be using it wrong. Either that or you need to package the info into the exception itself.
firedraco, I don't quite understand what you mean by (maybe due to lack of knowledge or experience):
If you need to have the same exception do multiple things then you might be using it wrong. Either that or you need to package the info into the exception itself.
What I am trying to say is that, how does the compiler choose the handler that is specific to the exception, if there is another exception that throws the same type?
That is exactly what I mean. Is there any other way in which you could use the other handler?
You could examine the contents of the exception in the innermost catch-clause, and if it isn't what the catch clause expects, rethrow (that is, use throw; with no arguments).
It's pretty common to use the same type exception (e.g. std::runtime_error or std::system_error) to signal different error conditions, the catch-clauses can sort it out.
PS: a couple simple rules to avoid common errors and maintenance headaches
1. throw by value, catch by (const) reference
2. only throw objects derived (directly or indirectly) from std::exception