Catch exception in parsing string to Number in CSharp

Description

The following code shows how to catch exception in parsing string to Number.

Example


using System;// ww w  .j av a2s  . c  om
using System.Data;


class Class1{
        static void Main(string[] args){
      string IsNotNum = "111west";
      string IsNum = "  +111  ";
      string IsFloat = "  23.11  ";
      string IsExp = "  +23 e+11  ";
      
      Console.WriteLine(int.Parse(IsNum));    
        Console.WriteLine(float.Parse(IsNum));    // 111
      Console.WriteLine(float.Parse(IsFloat));  // 23.11
      //Console.WriteLine(float.Parse(IsExp));  // throws
      
      try
      {
        Console.WriteLine(int.Parse(IsNotNum));
      }
      catch (FormatException e)
      {
        Console.WriteLine("Not a numeric value: {0}", e.ToString());  // throws
      }

        }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Data Types »




C# Data Types
Bool
Byte
Char
Decimal
Double
Float
Integer
Long
Short
String
C# Array
Array Example
Byte Array
C# Standard Data Type Format
BigInteger
Complex
Currency
DateTime
DateTimeOffset
DateTime Format Parse Convert
TimeSpan
TimeZone
Enum
Null
tuple
var