Basically, a code that catches an exception should know a few things:
- What happened?
- Is any specific action required
- After performing the above action, if it is performed, an exceptional condition is considered permitted.
- What condition will any applicable objects be in?
Unfortunately, many languages โโand frameworks, including C ++, Java, and .net, try to use one rather awkward kind of information (the type of an object of an excluded exception) to convey all three pieces of information, even if in practice they are often orthogonal in many ways. A particularly noteworthy complexity of this design is that several exceptional conditions arise at the same time, so that the handlers applicable to ANY of them must be launched, but the exception must continue to the stack until they are processed otchiki applicable to all of them.
Despite the limitations of type-based design, you need to work with it. When developing your own custom classes / interfaces and the exceptions that arise from them, you should try to use different types of exceptions to answer question No. 3- # 4 above, since these are questions that are most likely to be interesting to the caller. I would suggest that it might be desirable for classes to have a state variable or flag that might be invalid if an exception thrown inside the method is likely to leave the class in an invalid state, possibly using a pattern, for example:
... before doing anything that might cause object to enter invalid state even temporarily ...
if (state! = MyClassState.HappyIdle) throw new StateCorruptException (....);
state = MyClassState.UnhappyOrBusy;
... manipulate state in a fashion that will end up with a valid state when complete ...
state = MyClassState.HappyIdle;
If such a pattern is used sequentially, callers do not have to worry too much about the possibility that the operation that led to the exception could leave the object in a damaged state, so trying to continue the operation may lead to further data loss, if the object was damaged, but the caller the code ignored the exception that occurred when it happened, further attempts to use the object will fail.
Unfortunately, many classes are not well protected with the help of such guards, so it is unsafe to assume that unknown exceptions are "harmless." On the other hand, from a practical point of view, there is no approach that is reliable and safe. Either the risk that one code dies is useless for an exception that would actually be harmless, as well as the risk of damage to damaged data structures that go out of control and distort other data structures. A better exception system would have better alternatives, but not with the existing system.