Do you initialize variables outside of the try block?

Updated by Brady Stroud [SSW] 1 year ago. See history

123
<introEmbed body={<> You should initialize variables outside of the try block. </>} />
Cursor cur;
try {
// ...
cur = Cursor.Current; //Bad Code - initializing the variable inside the try block
Cursor.Current = Cursors.WaitCursor;
// ...
} finally {
Cursor.Current = cur;
}

❌ Figure: Bad Example: Because of the initializing code inside the try block. If it failed on this line then you will get a NullReferenceException in Finally

Cursor cur = Cursor.Current; //Good Code - initializing the variable outside the try block
try {
// ...
Cursor.Current = Cursors.WaitCursor;
// ...
} finally {
Cursor.Current = cur;
}

✅ Figure: Good Example : Because the initializing code is outside the try block

Acknowledgements

Adam Cogan
Related rules

Need help?

SSW Consulting has over 30 years of experience developing awesome software solutions.

We open source.Loving SSW Rules? Star us on GitHub. Star