Question about try/catch for null variables

  • Thread starter Thread starter raylopez99
  • Start date Start date
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
}
 
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
 
Back
Top