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

5

u/kmatt17 Feb 24 '19

If the initialisation of a fails, b will retain whatever it had. For example, if you default initialise the values of a and b to nullptr, then b will remain nullptr if a fails. If it wasn't default initialised, then b will be whatever was left over in memory (which is a bad practice; always set pointers to nullptr immediately if you don't have an initial value for them).

1

u/MCRusher Jun 05 '19

I wish new would zero-init all memory by default.