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

3

u/blazestorm_keebs Feb 28 '19

I've seen this pattern used in a massive codebase to ensure exceptions were caught at ABI boundaries (where we convert exceptions to error codes). Every single function had it, and it was weird if you didn't see it. This was far cleaner than the alternative.

1

u/CakeDay--Bot Mar 06 '19

*Eyy, another year! * It's your 2nd Cakeday blazestorm_keebs! hug