Question about try/catch for null variables

R

raylopez99

Is there a better way (faster, cleaner) of checking for a null than
the below? I tried various other ways (commented out) and they give
run-time errors.

treeView1.Node[999] does not exist, it's a null.

TX

RL

try
{
if (treeView1.Nodes[999] == null)
throw new ArgumentException("Node cannot be
null!");
}

//if ((this.treeView1.Nodes[999] == null)) //doesn't work,
compiles but run time error
//{
// TreeNode bogusTreeNode = treeView1.Nodes[999];
// MessageBox.Show("bogus node!!");
//}
//next line will will trigger exception "out of bounds",
run-time
//if (!(bogusTreeNode.Parent != null))
{ MessageBox.Show("bogus node!"); }

catch (ArgumentException ex)
{
// MessageBox.Show("exception! bogus node"); //works
}
 
I

Ignacio Machin ( .NET/ C# MVP )

Is there a better way (faster, cleaner) of checking for a null than
the below?  I tried various other ways (commented out) and they give
run-time errors.

treeView1.Node[999] does not exist, it's a null.

TX

RL

            try
            {
                if (treeView1.Nodes[999] == null)
                    throw new ArgumentException("Nodecannot be
null!");
            }

            //if ((this.treeView1.Nodes[999] == null)) //doesn't work,
compiles but run time error
            //{
            //    TreeNode bogusTreeNode = treeView1.Nodes[999];
            //    MessageBox.Show("bogus node!!");
            //}
            //next line will will trigger exception "out of bounds",
run-time
            //if (!(bogusTreeNode.Parent  != null))
{ MessageBox.Show("bogus node!"); }

            catch (ArgumentException ex)
            {
              //  MessageBox.Show("exception! bogus node"); //works
            }

what about treeView.Nodes.Count < 999
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top