Abstract exception super type

Posted by marcof on Programmers See other posts from Programmers or by marcof
Published on 2011-11-14T14:11:41Z Indexed on 2011/11/14 18:10 UTC
Read the original article Hit count: 514

If throwing System.Exception is considered so bad, why wasn't Exception made abstract in the first place?

That way, it would not be possible to call:

throw new Exception("Error occurred.");

This would enforce using derived exceptions to provide more details about the error that occurred.

For example, when I want to provide a custom exception hierarchy for a library, I usually declare an abstract base class for my exceptions:

public abstract class CustomExceptionBase : Exception
{
    /* some stuff here */
}

And then some derived exception with a more specific purpose:

public class DerivedCustomException : CustomExceptionBase
{
    /* some more specific stuff here */
}

Then when calling any library method, one could have this generic try/catch block to directly catch any error coming from the library:

try
{
    /* library calls here */
}
catch (CustomExceptionBase ex)
{
    /* exception handling */
}

Is this a good practice?

Would it be good if Exception was made abstract?

EDIT : My point here is that even if an exception class is abstract, you can still catch it in a catch-all block. Making it abstract is only a way to forbid programmers to throw a "super-wide" exception. Usually, when you voluntarily throw an exception, you should know what type it is and why it happened. Thus enforcing to throw a more specific exception type.

© Programmers or respective owner

Related posts about c#

Related posts about exception-handling