Quote:
Originally Posted by candybar
This depends on the platform/language but either way, this isn't always possible since the library you're using may throw exceptions even in relatively predictable situations and the logic for detecting this condition is not possible to implement in the client code or otherwise duplicative. I think what you're saying applies more for exception handling where the error occurs vs exception handling far away from where the error occurs. But even then, in situations where option/maybe types are not idiomatic or where multiple libraries you're using throw exceptions, it may be much easier to handle these different cases with a single error handler closer to where you need to report or log the error than in various places where the error may happen. It's hard to generalize because the expected level of robustness is so wildly different from one use case to another. If you're writing a service that is expected to serve billions of requests every day or a client app that needs to be deployed to millions of users without expectation of centralized logging, that's different from when you're writing some internal web app that has 10 active users.
Agree with all this. I'm more talking about situations where the API takes an input that is supposed to be an integer, say, and force-casts it from a string to an integer, throwing an exception that is then caught by a try-catch block which surrounds the whole method as a catchall. Maybe that's not what Craggoo is talking about but that sort of thing is pretty common. The speed issue is one reason it's bad but the main ones are:
- Specificity: If the force-cast throws an exception I may just want to return an error to the client and not log it, since that's expected behavior, whereas the same exception thrown elsewhere in the method may reflect a serious error that should be logged. As the method is maintained and other code is added to it, the risk that new code will add exceptions that will be silently mishandled increases.
- Explicitness/Maintainability: I can't easily tell from reading the code what will happen if the cast fails. I have to go dig into the exception handler and be knowledgeable enough about the language to know what the exception types are in various failure cases before I can tell what will happen. Obviously the really bad scenario here is that the exception is allowed to bubble up and is handled off in some random place in the code.