0

I am aware of how to raise exceptions and how to catch them, but how do you know when to raise a certain common exception such as KeyError or ValueError? And why couldn't you just always raise the generic Exception if any exception handling behaviour treats all exceptions the same?

I am not sure if this comes down to personal stylistic preference or if there is a best practice for this. For context, this question was prompted by writing a kind of switch statement for file names that follows this kind of logic (this is not my actual code):

if a:
  return b
elif c:
  return d
else:
  raise Exception("letter not a or c")

I know switch cases came in Python 3.10, but this is a question about exceptions rather than any specific coding problem.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
sobmortin
  • 55
  • 9
  • This particular example calls for using `dict` instead of complex if/elif/else and if the missing key should raise an exception it would/should be `KeyError`. For general discussion on when/should I use custom exception, check https://stackoverflow.com/q/57165380/4046632 – buran Feb 10 '22 at 11:14
  • "any exception handling behaviour treats all exceptions the same" That statement is false. – Sören Feb 10 '22 at 11:38
  • Wouldn't it depend on the exception handling you have written? – sobmortin Feb 10 '22 at 11:43
  • A search engine had this one in the top 3 for "site:stackoverflow.com Python raise exception"... – Peter Mortensen Apr 27 '22 at 10:32

0 Answers0