3 ms·
> I have written plenty of C# code that deals with exceptions, and it is a pain to do it correctly. Apart from null, it might very well be the biggest design mi
by jeswin 11y ago
> I have written plenty of C# code that deals with exceptions, and it is a pain to do it correctly. Apart from null, it might very well be the biggest design mistake of the language.
In user code (as opposed to framework code), Typed Exceptions are overrated.
Let's take these two cases:
1. End-User: Doesn't care if the Exception is a ParseException or an InvalidVersionException. Exception("Invalid number") and Exception("Version should be higher") is just as good enough for a message. Basically, for the end-user, the app crashed and that's it.
2. Programmer: Will have to open the debugger or check the code anyway.
I get it that it's useful in some cases, when you wanna send back some structured data to the caller. But in the vast majority of cases, the plain Exception class and Stack Traces suffice.
- AndrewDucker 11y agoAgreed. I rarely need a typed exception. The purpose of the exception is to say "Stop doing what you were doing, and head up the stack until you find a point where the work can recover from this and carry on." Generally speaking, that point doesn't care why the bunch of stuff five levels down went wrong. It just wants to report the error, and then either carry on with something, or let the user know what the problem was and decide if they want it to carry on. Very occasionally, the actual type of the exception is useful. But mostly I just don't care about typed Exceptions.
- vitalyd 11y agoSo this is more akin to panics, where you don't really care about handling the error but rather want to stop dead in the tracks. But take something like .NET's SocketException, which contains a SocketErrorCode property; you may very well want to take different action depending on the type of error this is. This may be as simple as changing the text of the error shown to user (with suggestions on how to fix), but could also be some code based recovery that takes different action depending on the type.
- scardine 11y agoI guess Python is an exception to this rule. Typed exceptions are not only idiomatic but deeply ingrained into the language core. Even basic primitives like loops use exceptions to control flow (StopIteration).
- olavk 11y agoWhat if you want to handle some exceptions in code? After all, this is why we throw exceptions rather than just call exit() every time something goes wrong. Eg. if this service call time out, we retry a few times. Without typed exceptions we have to perform some kind of string matching on the exception message.
- olivier1664 11y agoexit() is worst: in winForm, it's generally better to catch the exception on top level and show a MsgBox to the user without crashing. The user understand that his current action has failed, but he do not lost its input.