| Topic: |
DEVELOP > c-Plus-Plus |
| User: |
"Ralph Moritz" |
| Date: |
20 Dec 2006 06:14:35 AM |
| Object: |
Should an overloaded, non-member operator throw? |
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
.
|
|
| User: "Salt_Peter" |
|
| Title: Re: Should an overloaded, non-member operator throw? |
20 Dec 2006 11:29:25 PM |
|
|
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).
.
|
|
|
|

|
Related Articles |
|
|