C# - failed parse exception?

后端 未结 10 1314
春和景丽
春和景丽 2021-02-19 07:35

I am writing a program in C#, and I want to catch exceptions caused by converting \"\" (null) to int. What is the exception\'s name?

EDIT: I\'m not sur

10条回答
  •  南方客
    南方客 (楼主)
    2021-02-19 08:12

    Convert.ToInt32 does not throw a format exception ("input string is not in the correct format") on a null string. You can use that if it is acceptable for the result to be a 0 for a null string. (still pukes on empty string though)

            string s = null;
            int i = Convert.ToInt32(s);
    

    But if you expect a number to be in the box, you should either use TryParse (as was suggested) or a Validator of some kind to inform the user that they need to enter a number.

提交回复
热议问题