1

I have a code, lets say :

'''

try: 
    somecode()
except Exception as e:
   somelog()

'''

Is there a way to find out all the possible exceptions somecode() can throw so that I can handle them in an appropriate order.

Ronnie
  • 483
  • 1
  • 5
  • 18
  • This is defensive programming you cannot predict all possibilities that may go wrong even if you try.. there will be many left – Yugandhar Chaudhari Nov 05 '19 at 05:57
  • No, there is not. Good documentation can help limit “expected behavior per API contract”. Anyway, catching Exception gets them (almost) all anyway so.. – user2864740 Nov 05 '19 at 05:59
  • Thought not related to python this you may find useful https://stackoverflow.com/questions/4393197/erlangs-let-it-crash-philosophy-applicable-elsewhere – Yugandhar Chaudhari Nov 05 '19 at 06:04
  • *Expected* exceptions should be documented. Unexpected ones may still occur, and it’s debatable whether you should want to catch them. – deceze Nov 05 '19 at 07:39

2 Answers2

0

While you may not always be able to know every error that may happen, you can do quite a bit by thinking of common cases. This link is a good starter's guide with examples:

https://www.pythonforbeginners.com/error-handling/exception-handling-in-python1

For raising exceptions you predict in your own functions, this is a good starter guide:

https://www.programiz.com/python-programming/user-defined-exception

Finally, when you're working with built in functions or packages, they usually document what exceptions they raise. For example, look at the built in page for Python https://docs.python.org/3/library/functions.html And ctrl-f ValueError. A lot of docs will tell you what exceptions they raise but beyond that it's up to you to anticipate and guess based on your implementation and usage.

Hope that helps!

ufoxDan
  • 609
  • 4
  • 13
0

There are not so many exception types which you may have to consider for a single case. In case you are trying to access a file or accessing the database, the options are very few. The best practice is to keep track with the documentation. This will not take much time to know the name of the exception.

https://docs.python.org/3/tutorial/errors.html

Hasib A.
  • 73
  • 8