我有類主要包括收集字符串輸入,然後以特定格式輸出數據。該類的結果基本上是一個ToString()覆蓋。C#異常處理
與我的班級我有一個靜態方法string Print(string path)
從平面文件讀取輸入。然後解析這些輸入併爲平面文件中的每條記錄生成一個類的實例。然後對於類的每個實例,我調用class.ToString()並將其追加到最終在Print()
內返回的stringbuilder。
我確保每個記錄都有必要的值並且有適當的範圍,如果他們不需要拋出異常的話。我從來沒有做過異常處理,所以我想知道我想要做什麼甚至是可能的。我想要在stringbuilder中添加結束標記清理的東西,然後將異常文本預先加入到stringbuilder中,然後返回(Exception Error Text + stringbuilder.ToString()+ FooterStuff )。
編輯代碼:
它可能實際上不是一個好主意,拋出一個異常,我可能只需要使用try {}趕上{}捕捉異常,然後exception.message追加到stringbuilder的開始。但我不知道,例外對我來說是相當新的。
public class Record
{
public string Name;
public string Value;
...
private Dictionary<string, LogFormat> = new LogFormat.Table();
public static string Print()
{
Stringbuilder sb = new StringBuilder();
var k = ReadLog();
foreach (var x in k)
{
sb.Append(x.ToString());
}
return sb.ToString();
}
public override string ToString()
{
if (Table[Name].NeedsValue && (Value == String.Empty || Value == null))
{
throw new Exception();
}
return String.Format(Table[Name].Format, Attribute, Value);
}
}
public class LogFormat
{
public string Format;
public bool NeedsValue = false;
public Dictionary<string,LogFormat> Table()
{
Dictionary<string,LogFormat> dct = new Dictionary<string,LogFormat>();
dct.Add("Address", new LogFormat(){Format = "Street:{0}\nCity:{1}"});
...
return dct;
}
}
發佈您的代碼...... – 2010-10-19 05:25:45
好。給我一點時間。 – Shawn 2010-10-19 05:27:30