LoginSignup
0
1

More than 5 years have passed since last update.

Exception

Last updated at Posted at 2018-06-11

独自の例外クラスの定義

/// <summary>
/// Timeoutにより発生する例外クラスです。
/// </summary>
public class TimeoutException : Exception
{
    public int Timeout { get; }

    public TimeoutException(string msg) : base(msg)
    {
    }

    public TimeoutException(string msg, int timeout) : base(msg)
    {
        Timeout = timeout;
    }
}

例外をスロー

  • ExceptionにはStackTraceというプロパティが含まれている。
  • StackTraceでコード上のどの部分から例外が発生したかわかる。
  • "throw ex"よりも"throw"のほうが情報が多い。
  • "throw ex"と書くと、throwした時点のStackTraceに置き換わる。
try
{
    // test.txtが存在しない場合、例外が発生する
    using (StreamReader sr = new StreamReader("test.txt"))
    {
        while (sr.EndOfStream)
        {
            System.Diagnostics.Debug.WriteLine(sr.ReadLine());
        }
    }
}
catch(FileNotFoundException ex)
{
    //throw ex;
    throw;
}
  • "throw ex"と書くと、下記がStackTraceに含まれない。"throw"には含まれる。
場所 System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
場所 System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
場所 System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
場所 System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize, Boolean checkHost)
場所 System.IO.StreamReader..ctor(String path)
0
1
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
0
1