2

I have a template class with a custom exception:

MyClass<T>::MyException;

When using my class I only care whether the exception has been thrown so I can programmatically handle it. Therefore when I catch the exception, I don't bother to name it.

try {
   MyClass<T>::MyMethod ();
} catch (typename MyClass<T>::MyException) {
   //Act appropriately
}

I want to know if there is any difference when I add the reference operator, e.g.

} catch (typename MyClass::MyException &) {

In either case, I don't end up using the caught exception aside from identifying the type. Is there any tradeoff or performance hit for one vs. the other?

iamjboyd
  • 88
  • 7
  • What is `MyException` and why are you using `typename`? Also the single `:` is not right either. – crashmstr Mar 14 '14 at 14:35
  • Derive your exception from std::exception and catch via 'const std::exception&' or via 'const your_exception&' if you can do something useful (indicating a design flaw) –  Mar 14 '14 at 14:38

3 Answers3

6

Catching by value creates a copy of the exception object whether you use it or not. So don't. Always catch by reference. There is never a reason to catch by value.

As an aside, the typename keyword there is redundant, since there aren't any templates involved.

Sebastian Redl
  • 69,373
  • 8
  • 123
  • 157
1

In the first case:

catch (typename MyClass:MyException)

You'll invoke the copy constructor when catching. Also, if you've got another exception derived from MyException it will be sliced.

When you do:

catch (typename MyClass:MyException &)

You won't cause a copy to be made (so it's more efficient) and you can safely catch derived exceptions.

Sean
  • 60,939
  • 11
  • 97
  • 136
0

You should always catch exceptions by reference. It's just a good habit.

However, in this particular case, I don't think it matters. There are no slicing issues, because you do not name the caught exception object, so there are no members you might access. Whether the exception is copied twice should not matter much - it's just an exceptional case, and copying is cheap (if throwing is part of your normal program flow, then you have a bigger problem anyway).

The point is: catching by value doesn't buy you anything, either. Saving one character in the source code doesn't count :) Quite on the contrary, it creates a possible source of errors in the future.

Christian Hackl
  • 27,051
  • 3
  • 32
  • 62