我试图尝试捕获错误并显示成功消息,如果在xml文件中保存为true但我不知道如何绕过它。谁能帮忙。以下是我的代码:
dataentry.cs
try
{
teacher.Save();
if ()
{
MessageBox.Show("Teacher saved!!!","Success");
}
}
catch(Exception errorSave)
{
MessageBox.Show("Problem with savin file", "Error" + errorSave.Message);
}
person.cs
protected void Save(string typeName)
{
string targetDirectory = CreateTargetDirectory(typeName);
//2. Generate the path to the target file
string filePath = targetDirectory + ID + ".xml";
//3. Serialise the object
//4. Save the object to the target file
XmlSerializer xmlSerializer = new XmlSerializer(this.GetType());
using (FileStream dataStream = new FileStream(filePath, FileMode.Create))
{
xmlSerializer.Serialize(dataStream, this);
dataStream.Close();
}
}
teacher.cs
public class Teacher:Person
{
public void Save()
{
Save("teacher");
}
public static List<Teacher> Load()
{
return Load<Teacher>("teacher");
}
public decimal RatePerHour { get; set; }
public List<string> ClassNames { get; set; }
public string Subject { get; set; }
public string ClassName { get; set; }
}
答案 0 :(得分:3)
如果teacher.Save();
抛出异常,则会跳过try
块中的后续行。
如果teacher.Save();
没有抛出异常,您可以认为保存成功。
这两件事意味着您不需要在成功消息框周围添加if
语句。
try
{
teacher.Save();
MessageBox.Show("Teacher saved","Success");
}
catch(Exception saveError)
{
MessageBox.Show("Problem saving file", "Error" + saveError.Message);
}
答案 1 :(得分:1)
这个怎么样?
bool isSuccess = false;
string resultMessage = "File save {0}. {1}";
try
{
teacher.Save();
isSuccess = true;
resultMessage = string.Format(resultMessage, "succeeded", string.Empty);
}
catch(Exception errorSave)
{
//Log error here
//Set response message
resultMessage = string.Format(resultMessage, "failed", errorSave.Message);
}
finally
{
MessageBox.Show (resultMessage, isSuccess? "Success" : "Error");
}