The Right Approach to Exceptions

Jose Armando Garcia jsancio at gmail.com
Sun Feb 19 07:08:40 PST 2012


On Sun, Feb 19, 2012 at 12:51 PM, Alex Rønne Petersen
<xtzgzorex at gmail.com> wrote:
> On 19-02-2012 15:46, Andrei Alexandrescu wrote:
>>
>> On 2/19/12 8:44 AM, Alex Rønne Petersen wrote:
>>>
>>> On 19-02-2012 15:41, Andrei Alexandrescu wrote:
>>>>
>>>> That helps. This quite nicely illustrates that types don't necessarily
>>>> need to proliferate. Something not much more constraining can be done
>>>> today:
>>>>
>>>> try {
>>>> ...
>>>> } catch(IOException e)
>>>> {
>>>> if (e.errno !in subsetYouWantToHandle) throw e;
>>>> ...
>>>> }
>>>>
>>>>
>>>> Andrei
>>>
>>>
>>> As I pointed out on the pull request, this is *evil*. It resets the
>>> stack trace.
>>
>>
>> I understand, that's a good point. Could the matter be considered an
>> implementation issue?
>>
>> Andrei
>
>
> Unfortunately, I don't think so. As far as I am aware, there is no good way
> to solve the problem; you can't know whether the user intended to rethrow
> (and thus continue the stack trace) as opposed to doing a clean throw.
>
> You could say that if the throw statement is "throw new T();", then a new
> stack trace is created, and in all other cases, the stack trace is
> continued, however, this doesn't work universally (think: creating and
> returning an exception object in a function and then throwing it).
>

In general that is fine because in most cases you will use it as:

throw createException(... data ...);

What you can't do is cache exceptions:

immutable _IOExceptionCache = new IOException(...);

void someFunction(...) {
  throw _IOExceptionCache;
}

I think the best way to abstract exception creation is:

throwException(... data ...) {
 throw new Exception(...);
}

Thanks,
-Jose

> --
> - Alex


More information about the Digitalmars-d mailing list