2011-10-26 1 views
-2

私が設定ファイルから文字列を読み込んでいる場合、文字列が読み込まれているファイルに存在せず、例外が発生した場合にも同様のアプローチを使用します。しかし、もし私が文字列[]配列に対して同じことをしたいのであれば、サイズが分かっていないので、tryブロックの外側に '新しくする'ことはできません。C#で新しい配列を作成するtry-catch - どこで初期化するのですか?

tryブロック自体に新しくできません。どのように接近すべきですか?

string[] logContent; // can't new it up here as don't know the size 

       try 
       { 
        logContent = File.ReadAllLines(aLogFile); 
       } 
       catch 
       { 
        throw new Exception("LoggerStandard: Specified Logfile exists but could not be read."); 
       } 
+2

なぜ「新しいもの」にしたいですか? –

+0

なぜ人々はコメントなしでこれをdownvoteだろうか? goons。 – Glinkot

答えて

6

あなたはデフォルト値に初期化できます。デフォルトでは

string[] logContent = null; 
try 
{ 
    logContent = File.ReadAllLines(aLogFile); 
} 
catch 
{ 
    // Be careful with the error message here => there might be other reasons 
    // that the ReadAllLines threw an exception 
    throw new Exception("LoggerStandard: Specified Logfile exists but could not be read."); 
} 
+0

+1キャッチに関する注意。おそらく特定の例外を(適切な順序で)キャッチし、最後に一般的なキャッチを持っているでしょうか? – Tim

1

nullで初期化して確認することができます。

0

それがnullです。これがあなたのプログラムに適している場合はそのままにしておくか、必要に応じて任意の配列に初期化することができます。とにかく、tryブロックの内部での初期化に成功すると、これがオーバーライドされます。

0
string[] logContent=null; 
try 
{ 
    logContent = File.ReadAllLines(aLogFile);     
}     
catch     
{      
    throw new Exception("LoggerStandard: Specified Logfile exists but could not be read.");     
} 
関連する問題