0

I am writing a function for an API which I want to only be called from within a try statement so that developers can handle its custom exceptions.

Instead of just exaggerating the use of error handling in our documentation or using a #warning preprocessor directive, I was wondering if I could raise an error at compile time if the function is being called from outside a try statement?

Is is possible to do this?

All help is appreciated. Thanks in advance!

  • i'd be very surprised if that would work and i'd definitely consider it bad design. maybe if you'd be able to explain your case and reasons we could give you better options – Patrick Beynio Oct 26 '20 at 12:56
  • I highly doubt this is possible. You should be responsible for your code, and a consumer of your code should be responsible for theirs. The best you can do is give them detailed errors and custom exceptions, which it sounds like you are. – Jonesopolis Oct 26 '20 at 13:00
  • Checked exceptions would be awful in C#. Imagine modifying a low-level method to use an array, and then having to add `throws IndexOutOfRangeException` to it and every method that directly or indirectly uses it. Or having to add `throws DivideByZeroException` to any method that directly or indirectly did an integer division using a variable divisor. – Matthew Watson Oct 26 '20 at 13:20
  • 1
    You might be able to do something close by having an `Func` parameter on your method that handles errors. E.g. it would be called like `MyAPI(someInputParam, error => { /* code to handle error */ });` – Joe Sewell Oct 26 '20 at 13:22
  • The code in question is an abstract planning system where developers are responsible for defining the scene description, agents, domain, and methods themselves. The system will raise an exception if a critical error in the plan is identified, for example a required object for the plan is missing in the scene description. A developer will want to handle these exceptions by calling subroutines on their agents to solve the issues at hand, like locating an object. – Loui Eriksson Oct 26 '20 at 13:26

1 Answers1

0

I believe you are refering to checked exceptions and they are not supported by C#.

Check @Reed Copsey's answer here: [question]: No force of exception handling?

Ravicnet
  • 39
  • 5