Ralph Moritz wrote:
Hi,
I've written a class called ConfigParser, which can be used to parse
config files. (Surprise!) I have overloaded the shift operators to
mimic the std iostreams. My question is, should overloaded operators
throw or not? Both are non-member friends of ConfigParser.
Cheers,
Ralph
Sure, if you need them to throw, let them throw (ie:
std::runtime_error). As long as you use a try-catch block to capture
the thrown exception in context. Otherwise your program will call
terminate(). Silly example:
#include <iostream>
#include <ostream>
#include <stdexcept>
template< typename T >
class N
{
T m_t;
public:
N(T t) : m_t(t) { }
friend std::ostream&
operator<<(std::ostream& os, const N& r_n)
{
if(r_n.m_t 100 || r_n.m_t < 0)
throw std::runtime_error("op<<: out of range\n");
os << r_n.m_t;
return os;
}
};
int main()
{
try
{
N< int n(-1);
std::cout << n << std::endl;
}
catch( const std::exception& r_e )
{
std::cerr << "Error: " << r_e.what();
std::cerr << std::endl;
}
}
/*
Error: op<<: out of range
*/
If you plan to support a throw specification for the operator, which i
wouldn't recommend, use throw(std::runtime_error, std::bad_exception).