'Raising Python exceptions

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.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source