C#我怎么检查异常? [英] C# how can I check exception?

查看:69
本文介绍了C#我怎么检查异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如在控制台中我必须输入3个数据`

For example in console i must input 3 datas`

string,string,int



如果我写错了任何一个字,示例第一个数据我写为整数,它会警告我任何消息,例如`

.
if I write any of the words wrongly,for example first data i wrote as integer,it will warn me with any message,for example`

(some data are not correct)



我怎么能通过try catch写出Exception,这个条件我必须在try catch中写出来吗?



我尝试了什么:



也许我必须用int.TryParse写?


How can i write that Exception through try catch,which condition i must write in try catch?

What I have tried:

Maybe i must write with int.TryParse?

推荐答案

作为输入,数字是一个有效的字符串:你不会得到一个例外。

为输入参数序列编写自己的验证方法。

这样的方法可以返回一个 bool (比如 TryParse ),一个错误代码(在为了获得更多信息)甚至抛出一个 Exception (调用代码应该处理它)。
As input, a number is a valid string: you won't get an exception.
Write your own validation method for the sequence of input parameters.
Such method could return a bool (like TryParse), an error code (in order to get more information) or even thrown an Exception (that calling code should then handle it).


可以使用异常,但代码生成的异常代价很高,并且不应该真正用作验证,尤其是在转换失败的可能性时,例如验证用户的输入时。



相反,您应该使用string.split(google示例)将字符串拆分为逗号,然后遍历每个段并使用相应的TryParse函数,因此int.TryParse,bool .TryParse等依次验证它们。再次只是google有关如何使用int.tryParse等的示例。
You could use exceptions, but exceptions are expensive for the code to generate and shouldn't really be used as validation, especially when there is a likelihood the conversion will fail, such as when validating input from the user.

Instead you should use string.split (google for examples) to split the string on the comma, then go through each segment and use the appropriate TryParse function, so int.TryParse, bool.TryParse etc to validate them in turn. Again just google for examples of how to use int.tryParse etc.


For int you must try TryParse method.

For string u can typecast like :

int intA = 10;
string a = (string) intA;

but sometimes this may throw exceptions.

Instead try using : 

int intA = 10;
string a = Convert.ToString(intA);

The Convert.ToString() method will never throw exception and handles null as well when compared to typecasting.


这篇关于C#我怎么检查异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆