Topic: Exceptions and conversion functions


Author: ray@cse.ucsc.edu (Ray Swartz)
Date: 1995/05/18
Raw View
Is there some way to note in a derived class that a conversion
in the base class might throw an exception?

Here is an example:

class base {
public:
   base(int) throw(baseError);
   ...
};

class derived: public base {
public
    derived(base &);
    ...
};

If I now construct a derived object using an int argument:

int x = 5;

derived(x);

there is some chance that the conversion from x to base will
throw a baseError exception.

In Borland 4.5, noting that the derived constructor throws no
exceptions

derived(base &) throw();

didn't cause unexpected() to get thrown when base(int) threw one.

Since derived constructors don't have to note that conversions
to the base class via base class converters might throw exceptions, what
is the appropriate way to account for them, if at all?

Or, should converters not throw exceptions?

Ray Swartz





Author: clamage@Eng.Sun.COM (Steve Clamage)
Date: 1995/05/18
Raw View
In article 9il@darkstar.UCSC.EDU, ray@cse.ucsc.edu (Ray Swartz) writes:
>Is there some way to note in a derived class that a conversion
>in the base class might throw an exception?
>
>Here is an example:
>
>class base {
>public:
>   base(int) throw(baseError);
>   ...
>};
>
>class derived: public base {
>public
>    derived(base &);
>    ...
>};
>
>If I now construct a derived object using an int argument:
>
>int x = 5;
>
>derived(x);
>
>there is some chance that the conversion from x to base will
>throw a baseError exception.
>
>In Borland 4.5, noting that the derived constructor throws no
>exceptions
>
>derived(base &) throw();
>
>didn't cause unexpected() to get thrown when base(int) threw one.

I believe that is correct. The derived constructor was never entered,
since the exception was thrown as a result of evaluating its actual
argument. In other words, the "derived(x);" is equivalent to this:
 base temp(x),  // throws an exception
 derived(temp), // we never get here
 temp.base::~base();

In your specific case, wouldn't it make more sense to have a derived ctor
 derived::derived(int i) : base(i) { ... }

If base::base(int) throws an exception, that would count as derived
throwing an exception.
---
Steve Clamage, stephen.clamage@eng.sun.com