Reputation: 32162
I have a method in VB.NET which is just a helper for throwing exceptions. It will always throw an exception and never returns However the compiler does not detect this function as a terminating code path and thus I get warning if I use variables later on in the code that are not initialized via the exception code path.
Function Foo(y as Integer) As Boolean
dim x as boolean
if y > 10
x = 20
else
ThrowHelperFunction("Ouch")
end if
return x
End Function
The warning is that x is not initialized on all code paths.
Upvotes: 0
Views: 156
Reputation: 101150
Update:
There is a way since .NET Standard 2.1 (.NET 5 and newer):
[DoesNotReturn]
private void FailFast()
{
throw new InvalidOperationException();
}
Or conditionally:
private void FailFastIf([DoesNotReturnIf(true)] bool isNull)
{
if (isNull)
{
throw new InvalidOperationException();
}
}
Original answer:
I don't think that you can change that behavior. Instead you can do something like:
Function Foo(y as Integer) As Boolean
dim x as boolean
if y > 10
x = 20
else
throw CreateExceptionHelperFunction("Ouch")
end if
return x
End Function
That is, the helper function can still do some processing. But it will return an exception instead of throwing it.
Upvotes: 2
Reputation: 708
There is DoesNotReturnAttribute or this specific reason since .Net Core 2.1.
Upvotes: 1
Reputation: 31
try to initialize x with some default value like this. Boolean is Value Type and should never initialize with null value.
Function Foo(y as Integer) As Boolean
dim x as boolean
x = 0
if y > 10
x = 20
else
throw CreateExceptionHelperFunction("Ouch")
end if
return x
End Function
Upvotes: 1
Reputation: 1774
Try to use the following code (use Sub instead of Function)
Sub Foo(y As Integer)
Dim x As Boolean
If y > 10 Then
x = 20
Else
ThrowHelperFunction("Ouch")
End If
End Sub
Thanks.
Upvotes: 0