Reputation: 4736
what's a better way of doing the below try catch? Currently I have each WMI field in its own try catch statement.
I do not want to put the whole class into a massive try catch as I have issues with fields not displaying anything back (tried this and does not work well for what I am doing).
I have about 25 other WMI fields that I need to put in and am wondering if there is a simpler way of doing this?
private void cmbHdd_SelectedIndexChanged(object sender, EventArgs e)
ManagementObjectSearcher mosDisks = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive WHERE Model = '" + cmbHdd.SelectedItem + "'");
foreach (ManagementObject moDisk in mosDisks.Get())
{
try
{
lblSystemName.Text = "SystemName: " + moDisk["systemname"];
}
catch (Exception)
{
lblSystemName.Text = "SystemName: WMI Error"; ;
}
try
{
lblType.Text = "Type: " + moDisk["MediaType"].ToString();
}
catch (Exception)
{
lblType.Text = "Type: WMI Error";
}
}
Upvotes: 0
Views: 383
Reputation: 124696
You could use a helper method:
private static string GetMOValue(ManagementObject mo, string name)
{
try
{
object result = mo[name];
return result == null ? "" : result.ToString();
}
catch(Exception)
{
return "WMI Error";
}
}
...
lblSystemName.Text = GetMOValue(moDisk, "systemname");
lblType.Text = GetMOValue(moDisk, "MediaType");
Note you should probably catch a more specific exception (not sure what exceptions can be thrown by the ManagementObject indexer).
Upvotes: 1
Reputation: 6490
I feel that using these many try catch is not good. If i were u i would have done in following method..if try catch really needed.
private void cmbHdd_SelectedIndexChanged(object sender, EventArgs e)
ManagementObjectSearcher mosDisks = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive WHERE Model = '" + cmbHdd.SelectedItem + "'");
string current= string.Empty;
foreach (ManagementObject moDisk in mosDisks.Get())
{
try
{
current = "SystemName";
lblSystemName.Text = "SystemName: " + moDisk["systemname"];
current = "MediaType";
lblType.Text = "Type: " + moDisk["MediaType"].ToString();
}
catch(Exception)
{
//print "error in" + current;
}
}
Upvotes: 1
Reputation: 176886
I think erro occur when there is no data avaialbe for the given column in datatable
if (moDisk.Columns.Contains("systemname"))
{
lblSystemName.Text = "SystemName: " + moDisk["systemname"];
}
else
{
lblSystemName.Text = "SystemName: WMI Error";
}
Note : not sure this is datatable or not but you can code like this instead of catching exception for each value ... with the help of if ..else you can code this easily
Upvotes: 2