Timeline for Should custom exceptions live with the interface or the implementation?
Current License: CC BY-SA 4.0
4 events
| when toggle format | what | by | license | comment | |
|---|---|---|---|---|---|
| Aug 7, 2018 at 8:43 | comment | added | Flater | @James However, C# has no mechanism for enforcing the exceptions that an interface method can throw, You can implement this indirectly, if you only allow the exception to be created via a method (since you can enforce a method signature via interfaces). So instead of throw new CustomException() you do throw CreateException(). The syntax remains otherwise unchanged (constructor arguments become method parameters) and you can now enforce an exception type. As a quick and dirty example: interface IThrows<TException> where TException : Exception { TException CreateException(); } | |
| Aug 7, 2018 at 8:14 | history | edited | David Arno | CC BY-SA 4.0 | added 447 characters in body |
| Aug 7, 2018 at 8:14 | comment | added | James | "Do you anticipate that all implementations of IMyService should support throwing CustomException, or just MyService". Apart from unit testing implementations, yes all implementations will throw the exceptions (there is, as usual, only one implementation). However, C# has no mechanism for enforcing the exceptions that an interface method can throw, which makes it feel like a moot point. | |
| Aug 7, 2018 at 8:11 | history | answered | David Arno | CC BY-SA 4.0 |