0

This question is not why it is giving an error .. rather why it is not giving an error ...

private void Form1_Load(object sender, EventArgs e)
{
    Dictionary<string, string> dic = new Dictionary<string, string>();
    dic["666bytes"] = "ME";
    MessageBox.Show(dic["should_give_error"]);
}

This should give an error, right ? as dic["should_give_error"] is not present but it is not giving an error (the Form loads normally). But I can trap it with try..catch(KeyNotFoundException) block...how come ?

svick
  • 236,525
  • 50
  • 385
  • 514

3 Answers3

1

I suspect you aren't actually running Form1_Load. Here's a short but complete program to demonstrate the exception being thrown as expected:

using System;
using System.Collections.Generic;
using System.Windows.Forms;

class Test
{
    static void Main()
    {
        Form form = new Form();
        form.Load += Form1_Load;
        Application.Run(form);
    }

    private static void Form1_Load(object sender, EventArgs e)
    {
        Dictionary<string, string> dic = new Dictionary<string, string>();
        dic["666bytes"] = "ME";
        MessageBox.Show(dic["should_give_error"]);
    }
}

Compile and run that, and you get an exception dialog box.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Hi, yes I am running the right Form_Load event... I can do all other things during this event like change backcolor, show other Messagebox etc... –  Dec 02 '13 at 20:59
  • @666bytes: Did you try the code I gave? Because as I say, it definitely shows an exception box for me.... – Jon Skeet Dec 02 '13 at 21:20
0

You gotta read the documentation better. Quote:

// If a key does not exist, setting the indexer for that key 
// adds a new key/value pair.
openWith["doc"] = "winword.exe";

So, when you call dic["should_give_error"] the program goes, oh, that key doesn't exist, so let's create one. So it does, and returns an empty string.

Edit: Okay, it doesn't return the empty string when you try to get a non-existent key, but the load event can't throw exceptions under certain conditions. But if you leave it like it is, you should have an empty value for the key "should_give_error".

Kevin T
  • 216
  • 1
  • 6
0

I did found the answer (it's a BUG, not the answer I was expecting) and here are the references ...

  1. Reference # 1
  2. Reference # 2
  3. Reference # 3
Community
  • 1
  • 1