If have some framework that expects callbacks of a type like
void fcn(F& data);
It can handle exceptions of type ExF.
In my callback, I am using some third party library that throws exceptions of type ExL. So my callbacks look like
void fcn1(F& data)
{
try
{
// call library
}
catch(const ExL& ex)
{
ExF exf = make_ExF(ex);
throw exf;
}
}
Now I want to write more callbacks fcn2, fcn3, ... that use the library but do not want to repeat the same try/catch all the time. In particular, maybe I will add another
catch(const ExL2& ex)
block in the future for several callbacks. I cannot change the code (in particular the exception types) in the framework and the library. How can I avoid repeating the try/catch blocks?
Take advantage of the fact that while you are in a catch block, you have a "currently handled exception" that you can just throw;
again. This allows you to move the logic into another function
void except_translate() {
try
{
throw;
}
catch(const ExL& ex)
{
ExF exf = make_ExF(ex);
throw exf;
}
}
void fcn1(F& data)
{
try
{
// call library
}
catch(...)
{
except_translate();
}
}
This technique is known (for googling purposes) as a Lippincott function. It centralizes the error translation logic into one place, so you can easily extend that one function with another handler and it will translate it for all functions that use this utility.
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