By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,137 Members | 1,024 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,137 IT Pros & Developers. It's quick & easy.

Should an overloaded, non-member operator throw?

P: n/a
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

--
Ralph Moritz
Quantum Solutions Ph: +27 315 629 557
GPG Public Key: http://ralphm.info/public.gpg
Dec 21 '06 #1
Share this Question
Share on Google+
1 Reply


P: n/a

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).

Dec 21 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.