While updating an old exercise, I noticed tests where changed so that where the code needs to raise an exception, the exact type of that exception is checked. Thus, I can’t raise a subtype of those exceptions.
The same reason for any other expected behavior. Exercism uses a test driven development approach. The exercises are expected to have very specific behavior. That behavior is tested. The goal of the exercises is to write code that meets those expectations.
Well, ok, but IMO it is quite common to specialize an error so that you can catch that specific one.
For example, the specific exercise starting this asks for a ValueError to be raised. However, the same error could be raised automatically due to a bug in my code. If I do int("1337", 42) I get a ValueError (the 42 is the correct type, but the value, an integer base, is inappropriate for the int() function.
Now a client to my code would need to do this:
...
try:
parsed_number = PhoneNumber(number)
except ValueError:
print(f"Hey, get your {number} number right, I will have none of this!")
You see how the user will get frustrated being told off when their number might be just find, but there’s a bug in PhoneNumber?
What I can do instead is to define
class PhoneNumberError(ValueError): ...
With this, client code can catch this specific one if they want to distinguish the case from a potential bug.
I get your point, but perhaps we could allow for more nuance in the requirements and tests.
In general the advice is to avoid defining custom exceptions when the built-in exceptions suffice. That said, there are Python exercises that ask you to use custom exceptions.
Each exercise has a very specific set of expectations and requirements. The goal is not to make every exercise “production worthy”. Nor do we want to have people create custom exceptions for every exercise that does use exceptions. In a similar vein, we’ve explicitly removed some input validation from multiple exercises because that distracts from what the exercise is meant to be about.
Can exercises be extended with additional features? Absolutely. Does that improve the exercises? Often not.
Yeah ok, my example reason to create a custom exception is definitely not “production worthy”.
I wasn’t saying we should need write a custom exception, just that I’m not sure it adds value to the exercise to restrict to a built-in one. Anyway, fine, fine, I accept the point about having some requirement and adhering to it.