r/ProgrammerTIL • • Feb 24 '19

C++ [C++] TIL about function try-blocks

There exists a bit of syntax in C++ where functions can be written like so:

void TryCatchFunction()
try
{
	// do stuff
}
catch (...)
{
	// exceptions caught here
}

This is the equivalent of:

void TryCatchFunction()
{
	try
	{
		// do stuff
	}
	catch (...)
	{
		// exceptions caught here

            throw; // implicit rethrow
	}
}

This has been in the language for a long time yet seems to be quite an unknown feature of the language.

More information about them.

72 Upvotes

18 comments sorted by

View all comments

Show parent comment

8

u/jackwilsdon Feb 24 '19

Unless I'm missing something here, this is special syntax and not at all like an if without braces (you can't write functions without braces);

void main()
  printf("Hi"); // error: expected function body after function declarator

Adding try allows it to compile and run;

void main() try {
  printf("Hi"); // Hi
} catch (std::exception e) {}

Edit: formatting

0

u/Salink Feb 24 '19

You might be right but I'm pretty sure I've seen no brace functions for getters and setters in MSVC.