
On Fri, 2 Sept 2022 at 10:51, Steve Jorgensen <stevecjor@gmail.com> wrote:
Matthias Görgens wrote:
If the target of the call isn't in an appropriate state, isn't that a bug in the constructor that it allows you to construct objects that are in an invalid state? You should fix the object so that it is never in an invalid state rather than blaming the caller. You can't really do that with files that have been closed. Unless you disallow manual closing of files altogether. That being said, I'd suggest that people raise custom exception, so your callers can catch exactly what they want to handle. An generic exception like ValueError or the proposed InvalidStateError could be thrown by almost anything you call in your block, instead of just what you actually intend to catch.
It depends on context whether it makes sense to define a custom exception, and I agree that I frequently should define a custom exception. In that case though, it would still be nice to have an appropriate generic exception for that to inherit from, just as I would inherit from `ValueError` for a special case of a value error.
Can you describe a situation where you'd want to catch InvalidStateError from two unrelated libraries at the same time? That's the main value of an exception hierarchy - you don't have to worry about exactly which part of a block of code raised LookupError, you just catch it and cope (eg if you delve deep into a complex structure that has both lists and dicts, you can "except LookupError: not_found()" without caring which one failed). TBH I'm actually a bit confused as to how you'd cope with InvalidStateError anyway. In what situations would you be able to recover from such an error (other than generic "log the error and continue", which works fine with "except Exception")? ChrisA