文字列を他の型に変換するときの FormatException の処理

# 文字列を整数に変換

string を明示的に変換するために利用できるさまざまな方法があります integer に など:

  • `Convert.ToInt16();`
  • `Convert.ToInt32();`
  • `Convert.ToInt64();`
  • `int.Parse();`
  • しかし、これらすべてのメソッドは FormatException をスローします 、入力文字列に数字以外の文字が含まれている場合。このために、追加の例外処理を記述する必要があります (try..catch ) そのような場合に対処します。

    例による説明:

    それでは、入力を次のようにします:

    string inputString = "10.2";
    
    

    例 1: Convert.ToInt32()

    int convertedInt = Convert.ToInt32(inputString); // Failed to Convert 
    // Throws an Exception "Input string was not in a correct format."
    
    

    注: 他の言及されたメソッド、つまり Convert.ToInt16(); についても同じことが言えます と Convert.ToInt64();

    例 2: int.Parse()

    int convertedInt = int.Parse(inputString); // Same result "Input string was not in a correct format.
    
    

    これを回避するにはどうすればよいですか?

    前述のように、例外を処理するには通常 try..catch が必要です 以下に示すように:

    try
    {
        string inputString = "10.2";
        int convertedInt = int.Parse(inputString);
    }
    catch (Exception Ex)
    {
        //Display some message, that the conversion has failed.         
    }
    
    

    しかし、 try..catch を使用して 0 を指定したいシナリオがいくつかあるかもしれません。 入力が間違っている場合、(上記の方法に従う場合は、0 を割り当てる必要があります convertedInt へ catch ブロックから)。 このようなシナリオを処理するために、.TryParse() と呼ばれる特別なメソッドを利用できます。 .

    .TryParse() out への出力を提供する内部例外処理を持つメソッド パラメータを取得し、変換ステータスを示すブール値を返します (true 変換が成功した場合。 false 失敗した場合)。 戻り値に基づいて、変換ステータスを判断できます。一例を見てみましょう:

    使用法 1: 戻り値をブール変数に格納します

    
    int convertedInt; // Be the required integer
     bool isSuccessConversion = int.TryParse(inputString, out convertedInt);
    
    

    変数 isSuccessConversion を確認できます 実行後、変換ステータスを確認します。 false の場合、convertedInt の値 0 になります (0 が必要な場合は戻り値を確認する必要はありません 変換失敗の場合)。

    使い方 2: if で戻り値を確認

    if (int.TryParse(inputString, out convertedInt))
    {
        // convertedInt will have the converted value
        // Proceed with that
    }
    else 
    {
     // Display an error message
    }
    
    

    使い方 3: 戻り値をチェックせずに、戻り値を気にしない場合は、次を使用できます (変換されたかどうか、0 大丈夫です)

    int.TryParse(inputString, out convertedInt);
    // use the value of convertedInt
    // But it will be 0 if not converted
    
    

    No