1
2

More than 3 years have passed since last update.

【C#】try-catch

Last updated at Posted at 2020-07-09

★try-catchの記述方法
・tryブロックには例外1の可能性がある処理を記述
・catchブロックには例外1が発生した場合の処理を記述
・finallyブロックには例外1の有無関わらず実行する処理を記述

try
{
    //例外発生の可能性のある処理を記述
}
catch
{
    //例外が発生した場合の処理を記述
}
finally
{
    //例外の発生有無に関わらず実行する処理を記述
}


(例)

Test.txt
ささみの味噌煮
try-catchの記述方法
using System
class SampleTryCatch
{
    static void Main()
    {
        StreamReader sr = null;
        try
        {
            sr = new StreamReader(@"D:Test.txt",Encoding.GetEncoding("Shift_JIS"));
            string str = sr.ReadToEnd();
            Console.WriteLine(str);
        }
        catch (IOException e)
        {
            Console.WriteLine("例外が発生しました。");
            Console.WriteLine(e);
            return 0;
            //またはスルーさせる
            //throw;
        }
        finally
        {
            if(sr != null)
            {
                sr.Close();
                Console.WriteLine("ファイルを閉じました");
    }

実行結果

ささみの味噌煮
ファイルを閉じました

★例外フィルター
・catch句にwhen句を記述することによって例外条件を記述できる
・when句がある場合、catch句に同名型を複数使用できるが、上位から順に処理される

例外条件の記述方法
try
{
    //例外発生の可能性のある処理を記述
}
catch(例外) when(条件)
{
    //例外が発生した場合の処理を記述
}

  1. 例外クラスの一覧はこちら 

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2