Been using C# for about five years and only now did it strike me about the class visibility of custom exceptions. It's perfectly legal to write internal or even private nested exceptions like so:
internal class WhyDoThis : Exception { }
public class Foo { private class WhyWhyWhy : Exception { } }
So when you go about throwing these exceptions in your DLLs, only the (minority of) people doing decent (non pokemon) exception handling get their apps crashed.
So my question is, what's the purpose of such a pattern? Or why is this even legal?
The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch. The class Exception and any subclasses that are not also subclasses of RuntimeException are checked exceptions.
If you decide to define your own exception class. it must be a subclass of a Throwable class. You must decide which class you will extend. The two existing subclasses of Throwable are Exception and Error.
The purpose of a custom exception class is to integrate the look-up of localized message strings in a custom message catalog into the mechanism that is used for error reporting in the client infrastructure.
A simplistic answer would be: it's just as legal as any bad code can be.
I really can't think of anything else to say here that won't go beyond the scope of that question. That's just how it is. Anyone, at any time, can write code that even though can compile is just plain and simply awful.
EDIT:
I actually can think of one scenario where internal exceptions can have some use: for testing and asserting frameworks, like Code Contracts. But that's a very marginal case.
There nothing wrong from inheritance/visibility point of view to have internal/private exceptions. It is exactly the same as providing private class to implement public interface - whoever uses that object outside will not be able (short of reflection) to obtain details that are not exposed via public interface/base class.
So in exception case external callers will only be able to catch public base exception even if you fire very specific private exception. You may do that to provide custom ToString
for example.
Note that private/internal exceptions are probably bad idea as whole reason of throwing specific exception is to let someone to catch specific one.
Also check out Designing Custom Exceptions to make sure your exception classes are useful in all cases (like cross-domain exceptions require serialization).
One purpose would be for an exception that is used internally to an assembly (or even privately to a class), but where the exception never escapes the assembly (or the class). In that case, you wouldn't want it to become visible outside the assembly (or class).
In this case, it would obviously be a bug if the exception were to escape the assembly (or class).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With