C# - failed parse exception?

后端 未结 10 1318
春和景丽
春和景丽 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 07:48

    Depends on what you're using to do the conversion. For example, int.Parse will throw ArgumentNullException, FormatException, or OverflowException. Odds are it's ArgumentNullException you're looking for, but if that's an empty string rather than a null reference, it's probably going to be FormatException

    0 讨论(0)
  • 2021-02-19 07:48

    Just try it. This code:

    int.Parse("");
    

    Throws a FormatException.

    0 讨论(0)
  • 2021-02-19 07:49

    You're probably looking to get a System.InvalidCastException, although I think that'll depend on how you try to perform the conversion.

    That said, wouldn't it be quicker/easier to simply write the code and try it yourself? Particularly as you haven't specified how you'll be performing the conversion.

    0 讨论(0)
  • 2021-02-19 07:53

    If you can avoid it, do not code by exception!

    The exception name you are looking for is called a FormatException.

    However, it would be smarter to first do a TryParse on the object you are attempting to parse, e.g.

    int value;
    if(!int.TryParse("1", out value))
    {
        // You caught it without throwing an exception.
    }
    
    0 讨论(0)
  • 2021-02-19 07:57

    Exceptions are expensive. You should use int.TryParse. It will return the boolean false if the conversion fails.

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

    Let's have a look at the documentation (which is a much cleaner solution that "trying it out"):

    public static int Parse(string s)

    [...]

    Exceptions:

    • ArgumentNullException: s is null.
    • FormatException: s is not in the correct format.

    This should answer your question. As others have already mentioned, maybe you are asking the wrong question and want to use Int32.TryParse instead.

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