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 ?
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.
See more on this question at Stackoverflow