I did bit of researching while trying to find proper way to implement exceptions in my code I came accross
Throw by value, catch by reference
to be the recommended way of deal exceptions in C++ . I have a confusion about when the exception thrown gets out of scope.
I have following exception hierarchy
ConnectionEx is mother of all connection exceptions thrown by dataSender
ConnectionLostEx is one of the subclasses of ConnectionEx
so here is a sample code. In words DataSender instance is member of DataDistrubutor who calls functions on dataSender for example send() and DataSender throws ConnectionEx’s subclasses as exceptions in case of problems.
// dataSender send() function code chunk
try
{
// some problem occured
// create exception on stack and throw
ConnectionLostEx ex("Connection lost low signals", 102);
throw ex;
}
catch(ConnectionLostEx& e)
{
//release resources and propogate it up
throw ;
}
//A data distributor class that calls dataSender functions
try
{
// connect and send data
dataSender.send();
}
catch(ConnectionEx& ex)
{
// free resources
// Is the exception not out of scope here because it was created on stack of orginal block?
//propogate it further up to shows cause etc..
}
In C# or java we have a pointer like reference and that it valid all the way up, I am confused about the scope of exceptions given the exception is thrown by value when exactly does it get out of scope ??? and when caught as parent type ConnectionEx in this case can this be casted to get the real one back somwhere up in the chain of catch blocks ??
A copy of the exception is thrown, not the original object. There’s no need to instantiate a local variable and throw it; the idiomatic way to throw an exception is to instantiate it and throw it on the same line.