For example, one could avoid a possible run-time null exception in the case below by instantiating s as it is declared. For example, Dim s as String = "" Is there a reason for us to allow the possibility of a run-time exception? Perhaps it does not make sense for s to be ""? This is not a homework question. I am just curious.
Public Function X() As String
Dim s as String
Dim sMethod As String = X
Try
Dim vowels() As String = {"a", "e", "i", "o", "u"}
For Each vowel As String In vowels
s = "0"
Next
Catch ex As Exception
Throw System.Exception(ex)
End Try
Return s
End Function
- Editing to throw exception
Visual Studio seems to be smart enough to tell us that “A null reference exception could result at runtime.” which means some capable, professional developers ignored this warning. This leads me to think that must be for a reason. The developers have since moved on though so I can’t ask them. It might be something fundamental that I can’t understand. Please help me understand this if you will. (I can’t be the only person wondering about this.)
Suppose you don’t initialize your
Stringvariable. And there goes some processing. In the end you expect get a definitive value, which you return via aReturnstatement. If, for some reason, you forgot to account for a possible execution path, VS will warn you about possible null-reference exception. Then you may think to yourself: “oh yeah, how did I forget that?”For example, you have a
Functionthat converts aIntegerinto a word (limited practical use, so consider it just for demo purposes):In the above lines, you were unlucky to forget about the
Elsepath. Then suppose you want to run further processing on a resulting string:With 5 passed as an argument, you will get an exception at this point. If you instead listened to VS, you would have noticed a warning – underlined
retStringinReturn retStringline. So you could fix this problem without running your code.Now suppose you initialize
Dim retString As String = "". You will no longer see the warning, and have to debug your program to solve this issue. Depending on the complexity of your program, it may take much more effort.Bottom line – it is always better to spot problems in compile time, rather than run-time.
EDIT: Forgetting to initialize a variable can be intentional, for example why using TryGetValue. For this method, value
is passed uninitialized, according to documentation. However, VS does not know about this, so it will continue to show a warning, until you explicitly assign it toNothing:So this is a way to tell VS that yes, you know it is uninitialized, but for this particular scenario, it is intentional.