C# - failed parse exception?

后端 未结 10 1380
春和景丽
春和景丽 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:05

    You are going to get a FormatException if a parse fails. Why not use int.TryParse instead?

    0 讨论(0)
  • 2021-02-19 08:09

    As a side note, a simple way to find out the exception is to run it. When you encounter the error, it'll give you the exception name.

    0 讨论(0)
  • 2021-02-19 08:11

    When the exception fires you can see it's type. The smart thing to do is handle that case and display a graceful message to your user if possible.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题