我是C#的新手,從來沒有嘗試創建一個try catch塊,我得到一個錯誤,其中一個HybridDictionary中的錯誤指示「A keys already exists」,如何將.Adds放入一個try catch塊,而忽略它,如果鍵已經存在:Try Catch Block
這裏是原代碼與2個HybridDictionaries:
public MWRichTextBox() : base() {
// Initialize default text and background colors
textColor = RtfColor.Black;
highlightColor = RtfColor.White;
// Initialize the dictionary mapping color codes to definitions
rtfColor = new HybridDictionary();
rtfColor.Add(RtfColor.Aqua, RtfColorDef.Aqua);
rtfColor.Add(RtfColor.Black, RtfColorDef.Black);
rtfColor.Add(RtfColor.Blue, RtfColorDef.Blue);
rtfColor.Add(RtfColor.Fuchsia, RtfColorDef.Fuchsia);
rtfColor.Add(RtfColor.Gray, RtfColorDef.Gray);
rtfColor.Add(RtfColor.Green, RtfColorDef.Green);
rtfColor.Add(RtfColor.Lime, RtfColorDef.Lime);
rtfColor.Add(RtfColor.Maroon, RtfColorDef.Maroon);
rtfColor.Add(RtfColor.Navy, RtfColorDef.Navy);
rtfColor.Add(RtfColor.Olive, RtfColorDef.Olive);
rtfColor.Add(RtfColor.Purple, RtfColorDef.Purple);
rtfColor.Add(RtfColor.Red, RtfColorDef.Red);
rtfColor.Add(RtfColor.Silver, RtfColorDef.Silver);
rtfColor.Add(RtfColor.Teal, RtfColorDef.Teal);
rtfColor.Add(RtfColor.White, RtfColorDef.White);
rtfColor.Add(RtfColor.Yellow, RtfColorDef.Yellow);
rtfColor.Add(RtfColor.WhiteSmoke, RtfColorDef.WhiteSmoke);
// Initialize the dictionary mapping default Framework font families to
// RTF font families
rtfFontFamily = new HybridDictionary();
rtfFontFamily.Add(FontFamily.GenericMonospace.Name, RtfFontFamilyDef.Modern);
rtfFontFamily.Add(FontFamily.GenericSansSerif, RtfFontFamilyDef.Swiss);
rtfFontFamily.Add(FontFamily.GenericSerif, RtfFontFamilyDef.Roman);
rtfFontFamily.Add(FF_UNKNOWN, RtfFontFamilyDef.Unknown);
// Get the horizontal and vertical resolutions at which the object is
// being displayed
using(Graphics _graphics = this.CreateGraphics()) {
xDpi = _graphics.DpiX;
yDpi = _graphics.DpiY;
}
}
它是必不可少的,它在嘗試catch塊?我儘量避免他們在必要時,這裏是必要的。在我看來,最好在添加它之前檢查一個條目是否存在於集合中。 – hdougie
每次忽略異常時,一隻小貓都會死亡。不要使用'try' /'catch'來壓制錯誤。用它來處理_和_report_錯誤。 – David