如何获得价值引起异常 [英] how to get Value that cause exception
本文介绍了如何获得价值引起异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我怎样才能失败要转换的价值?在一般情况下,而不是在此单个特定示例情况
尝试
{
textBox1.Text =ABC;
INT ID = Convert.ToInt(textBox1.Text);
}
抓住
{
//为参数的值不知怎的,获取到.ToInt方法在这里
}
解决方案
您可以这样做?
INT ID;
如果(int.TryParse(textbox.Text,掉id)
{
//做一点事
}
其他
{
MessageBox.Show(textbox.Text);
}
您也可以使用如前面suggestet一试捕钓异常,并显示textbox.Text在catch。
编辑:(问题改变了方向后)
要说明的是无法转换,你可以做如下的价值。
字符串myvalue的=一些文本;
INT标识= 0;
尝试
{
ID = Convert.ToInt32(myvalue的);
}
赶上(FormatException E)
{
MessageBox.Show(的String.Format(无法转换{0}为intmyvalue的));
}
How can I get the value that failed to be converted? In general, and not in this single specific example case.
try
{
textBox1.Text = "abc";
int id = Convert.ToInt(textBox1.Text);
}
catch
{
// Somehow get the value for the parameter to the .ToInt method here
}
解决方案
You can do like this?
int id;
if(int.TryParse(textbox.Text, out id)
{
//Do something
}
else
{
MessageBox.Show(textbox.Text);
}
You can also use as earlier suggestet a try catch to catch a exception and show the textbox.Text in the catch.
EDIT : (After question changed direction) To show the value that was unable to convert you can do as following.
string myValue = "some text";
int id = 0;
try
{
id = Convert.ToInt32(myValue);
}
catch (FormatException e)
{
MessageBox.Show(String.Format("Unable to convert {0} to int", myValue));
}
这篇关于如何获得价值引起异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文