Exception annotations, similar to nullable, and knowing exception details at compile time. #6104
-
Have been thinking about the possibility of annotating Exception information in methods, similar to how nullable works. The goal would be to let the compiler determine (without knowing anything about how this could be achieved) what exceptions may be raised by a given method, and depending on how the method handles exceptions, the caller would be annotated with the same information. Maybe similar to #6079. Given the following method public void Method1(bool shouldThrow)
{
if(shouldThrow)
{
throw new Exception("Method 1");
}
} A caller of Method1 would know that there is a possible exception thrown. If the exception were not handled in a way that the compiler understands, the annotation would propagate to the caller. public void Method2()
{
Method1(...);
} Here Method2 is known to possibly throw an exception because of it's usage of Method1. A try catch could be used to prevent the annotation from propagating. public void Method3()
{
try
{
Method1(...);
}
catch(Exception) { }
} Here Method3 is known not to throw any exceptions. Some additional annotation information could be achieved by attributes that developers can use to either suppress or override the compiler generated information. // Option 1: An attribute on the class that overrides any compiler determined annotation.
[doesnotthrow]
public void Method2
{
bool shouldThrow = false;
// Option 2: Signal to the compiler that the appropriate checks have been made and Method1 is known not to throw.
#doesnotthrow
Method1(shouldThrow);
} Here the updated Method2 would have the same annotations as Method3. This example came up out of refactoring some older code to use nullable and discovering that some assumptions that were made in the past weren't obvious at the top or the caller tree. It would have been really nice to be able to track down the possible exception information with a system like above. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 6 replies
-
Looks like this maybe equivalent to the Java "throws" keyword, as discussed here. Agree it would be nice to see this functionality in C# with some of the automatic propagation suggested above. |
Beta Was this translation helpful? Give feedback.
-
Duplicate of #429, #4288, #2052, #2937, #947, and #3844. See also https://www.artima.com/articles/the-trouble-with-checked-exceptions, and interview with Anders on checked exceptions were not added to C# in 1.0. |
Beta Was this translation helpful? Give feedback.
Duplicate of #429, #4288, #2052, #2937, #947, and #3844. See also https://www.artima.com/articles/the-trouble-with-checked-exceptions, and interview with Anders on checked exceptions were not added to C# in 1.0.