Learning (not) to Handle Exceptions
Overall this seems like a good introduction to exceptions in Python, but I have a couple criticisms: -You almost never want an 'except' block that doesn't specify an exception type. lt will catch literally anything, including a lot of things you don't want: system exit, keyboard interrupt, out of memory errors, and more. -You rarely want to catch 'Exception', except possibly in top level code, for similar reasons. You should only catch the errors you're prepared to handle, and let higher level code sort out anything else. -Exception handlers that just print a static message are close to useless for debugging. Exception handlers that only print the error message aren't much better. You generally want to print the error type, message, any debugging data included with the error, and stack trace. Some of the articles in the example print the first three, but the stack trace is arguably the most important one since you'll see exactly where the error happened and what the call stack looked like. -Minor complaint - instead of this: try: file = open(...) doStuff(file) finally: file.close() Do this: with open(...) as file: doStuff(file) Or if it was a contrived example for readers, at least mention the better way to do it. :)
More on reddit.comWhat are some good real-world examples of exceptions in Python? (like what open source projects are a good example of exception usage?)
Most medium and bigger sized projects use exceptions, as do small projects. Look up the code for Python modules that are really popular, like requests or flask, and you'll find exception handling as well as custom exceptions. I can give you some of my projects as well as other projects that use exceptions if you'd like, so here:
https://github.com/TabulateJarl8/academiic-public/blob/4663a91a751545291f1b0855203dd3db4a0703a8/app.py#L209
https://github.com/TabulateJarl8/ti842py/blob/84c427579477c3a01c195245a2aef63c3ba079ea/ti842py/main.py#L21
https://github.com/willmcgugan/rich/blob/c9afafdd680831a43956906d56c78d9933aaf232/rich/console.py#L938
https://github.com/stub42/pytz/blob/df59d3af429d46ee575ab5d3a7fe3f8cd49a74bc/src/pytz/tzinfo.py#L7
https://gitlab.com/TurboWafflz/ImaginaryInfinity-Calculator/-/blob/d5013bf567b4d2b6a3d7fde069b70adcb6aa36a1/system/systemPlugins/pm.py#L399
Custom exceptions: https://github.com/psf/requests/blob/1466ad713cf84738cd28f1224a7ab4a19e50e361/requests/exceptions.py
More on reddit.com