Documente Academic
Documente Profesional
Documente Cultură
C++
If any statement in this block leads to an exception being thrown, the catch blocks after this block will handle the exception. If the program calls hmean() somewhere else outside this (and any other) try block, it will not have the opportunity to handle an exception.
In this case, the thrown exception is the string bad hmean() arguments: a = -b not allowed. The exception type can be a string, as in this case, or other C++ types. A class type is the usual choice (see example 2). Executing the throw is a bit like executing a return statement in that it terminates function execution. In this case, the throw passes program control back to main(). There, the program looks for an exception handler (following the try block) that matches the type of exception thrown !
*source: C++ Primer Plus
The argument of the catch block (char* s) denotes that this catch block handles thrown exceptions of type string. In this case, it means that the catch block will handle the exception: throw bad hmean() arguments: a = -b not allowed; In other words, s will point to the string bad hmean() arguments: a = -b not allowed and the result of the cout<<s statement will be printing that string on the screen.
The catch block looks a bit like a function definition, but it is not. The keyword catch identifies this is a handler, and char* s means that this handler matches a thrown exception that is a string. This declaration of s acts much like a function argument definition in that a matching thrown exception is assigned to s. Also, if an exception does match this handler, the program executes the code within the braces. If a program completes executing statements in a try block without any exceptions being thrown, it skips the catch block or blocks after the try block and goes to the first statement following the handlers.
*source: C++ Primer Plus
Types match: In the function hmean() we are throwing an exception object of type bad_hmean by calling the standart constructor of the class bad_hmean. The argument of the catch block is also of type bad_hmean