我正在尝试抓住System.ArgumentException
“网址不能为空。”并显示一条消息:
catch (System.ArgumentException errormsg)
{
string errorVar = Convert.ToString(errormsg);
if (errorVar == "System.ArgumentException: The URL cannot be empty.")
{
MessageBox.Show("The URL / Filename cannot be empty. Please check and try again");
}
else
{
MessageBox.Show("There is no message for this error:- " + errorVar);
}
}
目前,它一直在运行“Else”场景,消息框为:
注意:第153行= doc.Load(openFileDialog1.FileName);
有人可以帮助我让它运行“if”而不是“else”吗?
答案 0 :(得分:3)
您应该查看导致它的原因,而不是尝试解析异常。在这种情况下,问题是openFileDialog1.FileName
是empty
,所以,你应该做的是这样的:
try
{
if (string.IsNullOrEmpty(openFileDialog1.FileName))
{
MessageBox.Show("You need to select the file to open");
}
else
{
// Only attempt to do this if you know the user selected some value
doc.Load(openFileDialog1.FileName);
}
}
catch (ArgumentException ex)
{
//Show some error that is not caused by the URL being empty
}
作为一般规则,您需要在尝试使用之前验证用户输入。
答案 1 :(得分:0)
DispatchQueue.main.async() {
self.performSegue(withIdentifier: "GoToHomeFromSplash", sender: self)`
}
然后你可以比较它
string errorVar = errormsg.Message; //this would give you the error message
您还可以使用if (errorVar.Equals("The URL cannot be empty."))
或.Contains