The Right Approach to Exceptions
Juan Manuel Cabo
juanmanuel.cabo at gmail.com
Sun Feb 19 03:17:23 PST 2012
That proposed syntax is nicer than this, but at least you can do
it this way:
just call the same function from both catch blocks.
#!/usr/bin/rdmd
import std.stdio, std.utf, std.string;
void main() {
void handleStringAndUtf(Exception ex) {
if (typeid(ex).name == "std.utf.UTFException") {
// .. UtfException specific handling ..
writeln("length: ", (cast(UTFException)ex).len);
}
// .. handling of UtfException and StringException in common ..
writeln(ex.toString);
writeln(typeid(ex).name);
}
try {
throw new UtfException("");
//throw new StringException("aaaa");
} catch (StringException ex) {
handleStringAndUtf(ex);
} catch (UTFException ex) {
handleStringAndUtf(ex);
}
}
--jm
On Sunday, 19 February 2012 at 09:12:40 UTC, Jonathan M Davis
wrote:
> On Sunday, February 19, 2012 02:04:50 Andrei Alexandrescu wrote:
>> On 2/19/12 12:56 AM, Jonathan M Davis wrote:
> No. Sometimes you want to catch specific types and handle a
> subset of them in a particular way but don't want to handle
> _all_ of the exceptions with the same base class the same way.
> For instance, if you had the following and all of them are
> derived from FileException (save FileException itself):
>
> catch(e : FileNotFoundException, NotAFileException)
> {
> //...
> }
> catch(AccessDeniedException e)
> {
> //...
> }
> catch(FileException e)
> {
> //...
> }
>
> You want to handle certain exceptions differently and you want
> to handle some of them the same, but you don't want to handle
> all FileExceptions the same way. Without a way to put multiple
> exception types in the same block, you tend to end up with code
> duplication (and no I'm not necessarily advocating that we have
> those specific exception types - they're just examples).
>
> It's even worse if you don't have much of a hierarchy, since if
> _everything_ is derived from Exception directly, then catching
> the common type - Exception - would catch _everything_. For
> instance, what if you want to handle StringException and
> UTFException together but FileException differently? You can't
> currently do
>
> catch(e : StringException, UTFException)
> {
> //...
> }
> catch(FileException e)
> {
> //...
> }
>
> Right now, you'd have to have separate catch blocks for
> StringException and UTFException.
>
> A well-designed exception hierarchy reduces the problem
> considerably, because then there's a much higher chance that
> catching a common exception will catch what you want and not
> what you don't, but that doesn't mean that you're never going
> to run into cases where catching the common type doesn't work.
>
> - Jonathan M Davis
More information about the Digitalmars-d
mailing list