Re: Exception handling?
On 20 Feb, 19:45, "Alf P. Steinbach" <al...@start.no> wrote:
* mlt:
In the constructor of a class I run various test to check that the inpu=
t
data is valid, else I throw an exception:
...
...
MyTest(
int const k
, int const h
, U const & u
, U const & v
, P const & c
)
I hate that coding convention...
{
int controlnum = c.size() * c[0].size();
int basisnum = (u() - k) * (v.size() - h);
if(k<= 0 || h<=0)
throw std::invalid_argument("k h must be greater tha=
n zero");
if(uknots.size() <= 0)
throw std::invalid_argument("u was empty");
if(vknots.size() <= 0)
throw std::invalid_argument("v was empty");
if(controls.size() <= 0)
throw std::invalid_argument("c was empty");
...
...
}
The first thing that needs to be done is to catch the exceptions so the
error messages gets printed to the user. But how do I make sure the
right message is printed, do I make some sort of exception switch?
int main ()
{
try
{
getArgs (k, h, u, v, c);
Mytest (k, h, u, v, c);
}
catch (std::invalid_argument& e) // could catch std::exception
{
std::cerr << "invalid argument " << e.what() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
In a small program made just for your own use you simply use the
std::exception::what() method.
But in a larger program it's generally *not a good idea* to transfer UI m=
essages
in exceptions.
There are many reasons for that, including internationalization problems,=
and
that code that throws generally doesn't know anything about high level go=
als,
and that it would be in conflict with use of exceptions for programmers, =
and so on.
what would you typically throw?
Ask yourself, what business has the user knowing about arguments to MyTes=
t?
And by the way, for the specific tests above I'd use 'assert', not except=
ions.
you don't know what the source of the arguments is.
This might be some long running server that's been handed
a bunch of parameters by a human user. assert() may not
be appropriate.
--
Nick Keighley