1
try 
{ 
 if (!File.Exists("File.Ext")) 
    throw new FileNotFoundException(); 

} 
catch(FileNotFoundException e) 
{ 
   // your message here. 
} 

この投稿を書いている間、私は上記のコードを見つけました、私がbmpを読んでいるエラーをチェックしようとしている1つのブロックでそれを行う方法があるに違いないと思います

Bitmap b2;
b2 = new Bitmap("g:\\btmp1.bmp");

したがって、ファイルを「b2」に割り当てる際に問題が発生すると、エラーが発生します。

string notExst = "";
Bitmap b2;
try
{
    b2 = new Bitmap("g:\\ba.bmp");
}
catch (FileNotFoundException e)
{
    throw e.Tostring(); \\ would it be ok to 
 \\ msgbox.show(e.Tostring()) insted of throw ?

}

Try Catchで構文エラーが発生したと思いますが、正しい方法は何ですか?ありがとう。

ジョーイを編集した後、私はあなたの答えを理解していません。

ついに

public bool TryGetBitMap(string FilePath)
{
    string NotExstMsg = "The file: " + FilePath + "Could Not Be Found!";
    bool exst = false;
    if (!File.Exists(FilePath))
         MessageBox.Show(NotExstMsg);
    else exst = true;
    return exst;
}

private void ButScreenCupt_Click(object sender, EventArgs e)
{

    string FilePath1 = "g:\\a.bmp";
    string FilePath2 = "g:\\b.bmp";
    Bitmap b1, b2;
    bool isSuccess1 = TryGetBitMap(FilePath1);
    bool isSuccess2 = TryGetBitMap(FilePath2);
    if (isSuccess1 && isSuccess2)
    {
        b1 = new Bitmap(FilePath1);
        pictureBox1.Image = b1;
        b2 = new Bitmap(FilePath2);
        pictureBox2.Image = b2;
        dd = ComparingImages.Compare(b1, b2);

        MessageBox.Show(dd.ToString());
    }
}
4

4 に答える 4

2
Bitmap b2;
try
{
    b2 = new Bitmap("g:\\ba.bmp");
}
catch (FileNotFoundException notExst)
{
   //enter your message here
}

catch内で例外をスローする必要はありません。

于 2012-08-19T19:29:49.247 に答える
0

TryGetパターンを使用して独自のメソッドを作成できます。

bool isSuccess = TryGetBitMap("g:\\ba.bmp",b2);
于 2012-08-19T19:29:25.670 に答える
0

notExst 変数を宣言しないでください。

于 2012-08-19T19:30:55.210 に答える
0

@Jaguarが述べたように、Bitmapクラスによってスローされた場合、FileNotFoundExceptionをキャッチできます。例外処理により、コールスタックがアンワインドされます。if-elseステートメントを使用してファイルの存在を確認できる場合は、それが望ましいでしょう。

于 2012-08-19T19:32:46.977 に答える