I'm wondering when programmers use function try blocks. When is it useful?
void f(int i) try { if ( i < 0 ) throw "less than zero"; std::cout << "greater than zero" << std::endl; } catch(const char* e) { std::cout << e << std::endl; } int main() { f(1); f(-1); return 0; }
Output: (at ideone)
greater than zero less than zero
EDIT: As some people might think that the syntax of function defintion is incorrect (because the syntax doesn't look familiar), I've to say that no its not incorrect. Its called function-try-block. See §8.4/1 [dcl.fct.def] in the C++ Standard.
In simple words, in case of checked exception the compiler will force you to put a try catch or throws. In case of unchecked exception, compiler doesnt mind if you dont put try catches and throws. It is almost always a bad practice to put try catch in cases of unchecked exception like in the code.
Yes, It is possible to have a try block without a catch block by using a final block. As we know, a final block will always execute even there is an exception occurred in a try block, except System.
Place any code statements that might raise or throw an exception in a try block, and place statements used to handle the exception or exceptions in one or more catch blocks below the try block. Each catch block includes the exception type and can contain additional statements needed to handle that exception type.
The reason why your try catch block is failing is because an ajax request is asynchronous. The try catch block will execute before the Ajax call and send the request itself, but the error is thrown when the result is returned, AT A LATER POINT IN TIME. When the try catch block is executed, there is no error.
You use it in constructors to catch errors from initializers. Usually, you don't catch those errors, so this is a quite exceptional use.
Otherwise, it is useless: unless I'm proven wrong,
void f() try { ... } catch (...) { ... }
is strictly equivalent to
void f() { try { ... } catch (...) { ... } }
Function try block are useful for me in two contexts.
a) To have a catch all clause around main()
allowing to write small utilities without having to worry about local error handling:
int main() try { // ... return 0; } catch (...) { // handle errors return -1; }
which is clearly just syntactic sugar for having a try/catch inside main()
itself.
b) to handle exceptions thrown by base class constructors:
struct B { B() { /*might throw*/ } }; struct A : B { A() try : B() { // ... } catch (...) { // handle exceptions thrown from inside A() or by B() } };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With