Should an overloaded, non-member operator throw?

R

Ralph Moritz

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
 
S

Salt_Peter

Ralph said:
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::eek:stream&
operator<<(std::eek:stream& 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).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,534
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top