NullReferenceException クラス

定義

null オブジェクト参照を逆参照しようとした場合にスローされる例外。

public ref class NullReferenceException : Exception
public ref class NullReferenceException : SystemException
public class NullReferenceException : Exception
public class NullReferenceException : SystemException
[System.Serializable]
public class NullReferenceException : SystemException
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class NullReferenceException : SystemException
type NullReferenceException = class
    inherit Exception
type NullReferenceException = class
    inherit SystemException
[<System.Serializable>]
type NullReferenceException = class
    inherit SystemException
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type NullReferenceException = class
    inherit SystemException
Public Class NullReferenceException
Inherits Exception
Public Class NullReferenceException
Inherits SystemException
継承
NullReferenceException
継承
NullReferenceException
属性

注釈

値がnull型のメンバーにアクセスしようとすると、NullReferenceException例外がスローされます。 通常、 NullReferenceException 例外は開発者エラーを反映し、次のシナリオでスローされます。

C# では、null 条件演算子 (?.) または null 合体演算子 (??) を使用して、ほとんどのNullReferenceException例外を回避できます。 詳細については、「null 許容参照型」を参照してください。 次の C# の例では、null 許容コンテキストが無効になっていることを前提としています (推奨されません)。

  • 参照型のインスタンス化を忘れた。 次の例では、 names は宣言されますが、インスタンス化されることはありません (影響を受ける行はコンパイルされないため、C# の例ではコメント アウトされます)。

    using System.Collections.Generic;
    
    public class UseBeforeAssignExample
    {
        public static void Main(string[] args)
        {
            int value = int.Parse(args[0]);
            List<string> names;
            if (value > 0)
                names = [];
    
            //names.Add("Major Major Major");
        }
    }
    
    // Compilation displays a warning like the following:
    //    warning BC42104: Variable //names// is used before it
    //    has been assigned a value. A null reference exception could result
    //    at runtime.
    //
    //          names.Add("Major Major Major")
    //          ~~~~~
    // The example displays output like the following output:
    //    Unhandled Exception: System.NullReferenceException: Object reference
    //    not set to an instance of an object.
    //       at UseBeforeAssignExample.Main()
    
    open System
    
    [<EntryPoint>]
    let main args =
        let value = Int32.Parse args[0]
        // Set names to null, don't initialize it. 
        let mutable names = Unchecked.defaultof<ResizeArray<string>>
        if value > 0 then
            names <- ResizeArray()
        names.Add "Major Major Major"
        0
    // Compilation does not display a warning as this is an extremely rare occurance in F#.
    // Creating a value without initalizing either requires using 'null' (not possible
    // on types defined in F# without [<AllowNullLiteral>]) or Unchecked.defaultof.
    //
    // The example displays output like the following output:
    //    Unhandled Exception: System.NullReferenceException: Object reference
    //    not set to an instance of an object.
    //       at Example.main()
    
    Imports System.Collections.Generic
    
    Module Example
       Public Sub Main()
          Dim names As List(Of String)
          names.Add("Major Major Major")       
       End Sub
    End Module
    ' Compilation displays a warning like the following:
    '    Example1.vb(10) : warning BC42104: Variable 'names' is used before it 
    '    has been assigned a value. A null reference exception could result 
    '    at runtime.
    '    
    '          names.Add("Major Major Major")
    '          ~~~~~
    ' The example displays output like the following output:
    '    Unhandled Exception: System.NullReferenceException: Object reference 
    '    not set to an instance of an object.
    '       at Example.Main()
    

    一部のコンパイラは、このコードをコンパイルするときに警告を発行します。 他のユーザーはエラーを発行し、コンパイルは失敗します。 この問題に対処するには、オブジェクトの値が nullされないようにオブジェクトをインスタンス化します。 次の例では、型のクラス コンストラクターを呼び出すことによってこれを行います。

    using System.Collections.Generic;
    
    public class AnotherExample
    {
        public static void Main()
        {
            List<string> names = ["Major Major Major"];
        }
    }
    
    let names = ResizeArray()
    names.Add "Major Major Major"
    
    Imports System.Collections.Generic
    
    Module Example
       Public Sub Main()
          Dim names As New List(Of String)()
          names.Add("Major Major Major")       
       End Sub
    End Module
    
  • 初期化する前に配列を次元化するのを忘れた。 次の例では、 values は整数配列として宣言されていますが、含まれる要素の数は指定されていません。 したがって、その値を初期化しようとすると、 NullReferenceException 例外がスローされます。

    int[] values = null;
    for (int ctr = 0; ctr <= 9; ctr++)
        values[ctr] = ctr * 2;
    
    foreach (int value in values)
        Console.WriteLine(value);
    
    // The example displays the following output:
    //    Unhandled Exception:
    //       System.NullReferenceException: Object reference not set to an instance of an object.
    //       at Array3Example.Main()
    
    let values: int[] = null
    for i = 0 to 9 do
        values[i] <- i * 2
    
    for value in values do
        printfn $"{value}"
    // The example displays the following output:
    //    Unhandled Exception:
    //       System.NullReferenceException: Object reference not set to an instance of an object.
    //       at <StartupCode$fs>.main()
    
    Module Example
       Public Sub Main()
           Dim values() As Integer
           For ctr As Integer = 0 To 9
              values(ctr) = ctr * 2
           Next
              
           For Each value In values
              Console.WriteLine(value)
           Next      
       End Sub
    End Module
    ' The example displays the following output:
    '    Unhandled Exception: 
    '       System.NullReferenceException: Object reference not set to an instance of an object.
    '       at Example.Main()
    

    次の例のように、初期化する前に配列内の要素の数を宣言することで、例外を排除できます。

    int[] values = new int[10];
    for (int ctr = 0; ctr <= 9; ctr++)
        values[ctr] = ctr * 2;
    
    foreach (int value in values)
        Console.WriteLine(value);
    
    // The example displays the following output:
    //    0
    //    2
    //    4
    //    6
    //    8
    //    10
    //    12
    //    14
    //    16
    //    18
    
    let values = Array.zeroCreate<int> 10
    for i = 0 to 9 do
        values[i] <- i * 2
    
    for value in values do
        printfn $"{value}"
    // The example displays the following output:
    //    0
    //    2
    //    4
    //    6
    //    8
    //    10
    //    12
    //    14
    //    16
    //    18
    
    Module Example
       Public Sub Main()
           Dim values(9) As Integer
           For ctr As Integer = 0 To 9
              values(ctr) = ctr * 2
           Next
              
           For Each value In values
              Console.WriteLine(value)
           Next      
       End Sub
    End Module
    ' The example displays the following output:
    '    0
    '    2
    '    4
    '    6
    '    8
    '    10
    '    12
    '    14
    '    16
    '    18
    

    配列の宣言と初期化の詳細については、「 配列配列」を参照してください。

  • メソッドから null 戻り値を取得し、返された型でメソッドを呼び出します。 これは、ドキュメント エラーの結果である場合があります。ドキュメントは、メソッド呼び出しが nullを返すことができることに注意できません。 それ以外の場合、コードでは、メソッドが常に null 以外の値を返すと誤って想定しています。

    次の例のコードでは、Array.Find メソッドは、FirstName フィールドが検索文字列と一致するオブジェクトPerson常に返されることを前提としています。 一致するものがないため、ランタイムは NullReferenceException 例外をスローします。

    public static void NoCheckExample()
    {
        Person[] persons = Person.AddRange([ "Abigail", "Abra",
                                          "Abraham", "Adrian", "Ariella",
                                          "Arnold", "Aston", "Astor" ]);
        string nameToFind = "Robert";
        Person found = Array.Find(persons, p => p.FirstName == nameToFind);
        Console.WriteLine(found.FirstName);
    }
    
    // The example displays the following output:
    //       Unhandled Exception: System.NullReferenceException:
    //       Object reference not set to an instance of an object.
    
    open System
    
    type Person(firstName) =
        member _.FirstName = firstName
    
        static member AddRange(firstNames) =
            Array.map Person firstNames
    
    let persons = 
        [| "Abigail"; "Abra"; "Abraham"; "Adrian"
           "Ariella"; "Arnold"; "Aston"; "Astor" |]
        |> Person.AddRange
    
    let nameToFind = "Robert"
    let found = Array.Find(persons, fun p -> p.FirstName = nameToFind)
    
    printfn $"{found.FirstName}"
    
    // The example displays the following output:
    //       Unhandled Exception: System.NullReferenceException:
    //       Object reference not set to an instance of an object.
    //          at <StartupCode$fs>.main()
    
    Module Example
       Public Sub Main()
          Dim persons() As Person = Person.AddRange( { "Abigail", "Abra",
                                                       "Abraham", "Adrian",
                                                       "Ariella", "Arnold", 
                                                       "Aston", "Astor" } )    
          Dim nameToFind As String = "Robert"
          Dim found As Person = Array.Find(persons, Function(p) p.FirstName = nameToFind)
          Console.WriteLine(found.FirstName)
       End Sub
    End Module
    
    Public Class Person
       Public Shared Function AddRange(firstNames() As String) As Person()
          Dim p(firstNames.Length - 1) As Person
          For ctr As Integer = 0 To firstNames.Length - 1
             p(ctr) = New Person(firstNames(ctr))
          Next   
          Return p
       End Function
       
       Public Sub New(firstName As String)
          Me.FirstName = firstName
       End Sub 
       
       Public FirstName As String
    End Class
    ' The example displays the following output:
    '       Unhandled Exception: System.NullReferenceException: 
    '       Object reference not set to an instance of an object.
    '          at Example.Main()
    

    この問題に対処するには、次の例のように、メソッドの戻り値をテストして、メンバーを呼び出す前にメソッドが null されていないことを確認します。

    public static void ExampleWithNullCheck()
    {
        Person[] persons = Person.AddRange([ "Abigail", "Abra",
                                          "Abraham", "Adrian", "Ariella",
                                          "Arnold", "Aston", "Astor" ]);
        string nameToFind = "Robert";
        Person found = Array.Find(persons, p => p.FirstName == nameToFind);
        if (found != null)
            Console.WriteLine(found.FirstName);
        else
            Console.WriteLine($"'{nameToFind}' not found.");
    }
    
    // The example displays the following output:
    //        'Robert' not found
    
    open System
    
    [<AllowNullLiteral>]
    type Person(firstName) =
        member _.FirstName = firstName
    
        static member AddRange(firstNames) =
            Array.map Person firstNames
    
    let persons = 
        [| "Abigail"; "Abra"; "Abraham"; "Adrian"
           "Ariella"; "Arnold"; "Aston"; "Astor" |]
        |> Person.AddRange
    
    let nameToFind = "Robert"
    let found = Array.Find(persons, fun p -> p.FirstName = nameToFind)
    
    if found <> null then
        printfn $"{found.FirstName}"
    else 
        printfn $"{nameToFind} not found."
    
    // Using F#'s Array.tryFind function
    // This does not require a null check or [<AllowNullLiteral>]
    let found2 = 
        persons |> Array.tryFind (fun p -> p.FirstName = nameToFind)
    
    match found2 with
    | Some firstName ->
        printfn $"{firstName}"
    | None ->
        printfn $"{nameToFind} not found."
    
    // The example displays the following output:
    //        Robert not found.
    //        Robert not found.
    
    Module Example
       Public Sub Main()
          Dim persons() As Person = Person.AddRange( { "Abigail", "Abra",
                                                       "Abraham", "Adrian",
                                                       "Ariella", "Arnold", 
                                                       "Aston", "Astor" } )    
          Dim nameToFind As String = "Robert"
          Dim found As Person = Array.Find(persons, Function(p) p.FirstName = nameToFind)
          If found IsNot Nothing Then
             Console.WriteLine(found.FirstName)
          Else
             Console.WriteLine("{0} not found.", nameToFind)
          End If   
       End Sub
    End Module
    
    Public Class Person
       Public Shared Function AddRange(firstNames() As String) As Person()
          Dim p(firstNames.Length - 1) As Person
          For ctr As Integer = 0 To firstNames.Length - 1
             p(ctr) = New Person(firstNames(ctr))
          Next   
          Return p
       End Function
       
       Public Sub New(firstName As String)
          Me.FirstName = firstName
       End Sub 
       
       Public FirstName As String
    End Class
    ' The example displays the following output:
    '       Robert not found
    
  • 式 (メソッドまたはプロパティの一覧を連結するなど) を使用して値を取得し、値が nullされているかどうかを確認しても、ランタイムは引き続き NullReferenceException 例外をスローします。 これは、式の中間値の 1 つが nullを返しているために発生します。 その結果、 null のテストは評価されません。

    次の例では、Page オブジェクトによって表示される Web ページに関する情報をキャッシュするPages オブジェクトを定義します。 Example.Mainメソッドは、現在の Web ページに null 以外のタイトルがあるかどうかをチェックし、存在する場合はタイトルを表示します。 ただし、このチェックにもかかわらず、メソッドは NullReferenceException 例外をスローします。

    public class Chain1Example
    {
        public static void Main()
        {
            var pages = new Pages();
            if (!string.IsNullOrEmpty(pages.CurrentPage.Title))
            {
                string title = pages.CurrentPage.Title;
                Console.WriteLine($"Current title: '{title}'");
            }
        }
    }
    
    public class Pages
    {
        readonly Page[] _page = new Page[10];
        int _ctr = 0;
    
        public Page CurrentPage
        {
            get { return _page[_ctr]; }
            set
            {
                // Move all the page objects down to accommodate the new one.
                if (_ctr > _page.GetUpperBound(0))
                {
                    for (int ndx = 1; ndx <= _page.GetUpperBound(0); ndx++)
                        _page[ndx - 1] = _page[ndx];
                }
                _page[_ctr] = value;
                if (_ctr < _page.GetUpperBound(0))
                    _ctr++;
            }
        }
    
        public Page PreviousPage
        {
            get
            {
                if (_ctr == 0)
                {
                    if (_page[0] is null)
                        return null;
                    else
                        return _page[0];
                }
                else
                {
                    _ctr--;
                    return _page[_ctr + 1];
                }
            }
        }
    }
    
    public class Page
    {
        public Uri URL;
        public string Title;
    }
    
    // The example displays the following output:
    //    Unhandled Exception:
    //       System.NullReferenceException: Object reference not set to an instance of an object.
    //       at Chain1Example.Main()
    
    open System
    
    type Page() =
        [<DefaultValue>]
        val mutable public URL: Uri
        [<DefaultValue>]
        val mutable public Title: string
    
    type Pages() =
        let pages = Array.zeroCreate<Page> 10
        let mutable i = 0
    
        member _.CurrentPage
            with get () = pages[i]
            and set (value) =
                // Move all the page objects down to accommodate the new one.
                if i > pages.GetUpperBound 0 then
                    for ndx = 1 to pages.GetUpperBound 0 do
                        pages[ndx - 1] <- pages[ndx]
    
                pages[i] <- value
                if i < pages.GetUpperBound 0 then
                    i <- i + 1
    
        member _.PreviousPage =
            if i = 0 then
                if box pages[0] = null then
                    Unchecked.defaultof<Page>
                else
                    pages[0]
            else
                i <- i - 1
                pages[i + 1]
    
    let pages = Pages()
    if String.IsNullOrEmpty pages.CurrentPage.Title |> not then
        let title = pages.CurrentPage.Title
        printfn $"Current title: '{title}'"
    
    
    // The example displays the following output:
    //    Unhandled Exception:
    //       System.NullReferenceException: Object reference not set to an instance of an object.
    //       at <StartupCode$fs>.main()
    
    Module Example
       Public Sub Main()
          Dim pages As New Pages()
          Dim title As String = pages.CurrentPage.Title
       End Sub
    End Module
    
    Public Class Pages 
       Dim page(9) As Page
       Dim ctr As Integer = 0
       
       Public Property CurrentPage As Page
          Get
             Return page(ctr)
          End Get
          Set
             ' Move all the page objects down to accommodate the new one.
             If ctr > page.GetUpperBound(0) Then
                For ndx As Integer = 1 To page.GetUpperBound(0)
                   page(ndx - 1) = page(ndx)
                Next
             End If    
             page(ctr) = value
             If ctr < page.GetUpperBound(0) Then ctr += 1 
          End Set
       End Property
       
       Public ReadOnly Property PreviousPage As Page
          Get
             If ctr = 0 Then 
                If page(0) Is Nothing Then
                   Return Nothing
                Else
                   Return page(0)
                End If   
             Else
                ctr -= 1
                Return page(ctr + 1)
             End If
          End Get
       End Property         
    End Class
    
    Public Class Page
       Public URL As Uri
       Public Title As String
    End Class
    ' The example displays the following output:
    '    Unhandled Exception: 
    '       System.NullReferenceException: Object reference not set to an instance of an object.
    '       at Example.Main()
    

    ページ情報がキャッシュに格納されていない場合、 pages.CurrentPagenull を返すので、例外がスローされます。 次の例のように、現在のPage オブジェクトの Title プロパティを取得する前に、CurrentPage プロパティの値をテストすることで、この例外を修正できます。

    var pages = new Pages();
    Page current = pages.CurrentPage;
    if (current != null)
    {
        string title = current.Title;
        Console.WriteLine($"Current title: '{title}'");
    }
    else
    {
        Console.WriteLine("There is no page information in the cache.");
    }
    
    // The example displays the following output:
    //       There is no page information in the cache.
    
    let pages = Pages()
    let current = pages.CurrentPage
    if box current <> null then
        let title = current.Title
        printfn $"Current title: '{title}'"
    else
        printfn "There is no page information in the cache."
    // The example displays the following output:
    //       There is no page information in the cache.
    
    Module Example
       Public Sub Main()
          Dim pages As New Pages()
          Dim current As Page = pages.CurrentPage
          If current IsNot Nothing Then 
             Dim title As String = current.Title
             Console.WriteLine("Current title: '{0}'", title)
          Else
             Console.WriteLine("There is no page information in the cache.")
          End If   
       End Sub
    End Module
    ' The example displays the following output:
    '       There is no page information in the cache.
    
  • 参照型を含む配列の要素を列挙すると、いずれかの要素を処理しようとすると、 NullReferenceException 例外がスローされます。

    次の例では、文字列配列を定義します。 for ステートメントは、配列内の要素を列挙し、文字列を表示する前に各文字列のTrim メソッドを呼び出します。

    string[] values = [ "one", null, "two" ];
    for (int ctr = 0; ctr <= values.GetUpperBound(0); ctr++)
        Console.Write("{0}{1}", values[ctr].Trim(),
                      ctr == values.GetUpperBound(0) ? "" : ", ");
    Console.WriteLine();
    
    // The example displays the following output:
    //    Unhandled Exception:
    //       System.NullReferenceException: Object reference not set to an instance of an object.
    
    open System
    
    let values = [| "one"; null; "two" |]
    for i = 0 to values.GetUpperBound 0 do
        printfn $"""{values[i].Trim()}{if i = values.GetUpperBound 0 then "" else ", "}"""
    printfn ""
    // The example displays the following output:
    //    Unhandled Exception:
    //       System.NullReferenceException: Object reference not set to an instance of an object.
    //       at <StartupCode$fs>.main()
    
    Module Example
       Public Sub Main()
          Dim values() As String = { "one", Nothing, "two" }
          For ctr As Integer = 0 To values.GetUpperBound(0)
             Console.Write("{0}{1}", values(ctr).Trim(), 
                           If(ctr = values.GetUpperBound(0), "", ", ")) 
          Next
          Console.WriteLine()
       End Sub
    End Module
    ' The example displays the following output:
    '    Unhandled Exception: System.NullReferenceException: 
    '       Object reference not set to an instance of an object.
    '       at Example.Main()
    

    この例外は、配列の各要素に null 以外の値が含まれている必要があり、配列要素の値が実際には null場合に発生します。 次の例に示すように、その要素に対して操作を実行する前に要素が null されているかどうかをテストすることで、例外を排除できます。

    string[] values = [ "one", null, "two" ];
    for (int ctr = 0; ctr <= values.GetUpperBound(0); ctr++)
        Console.Write("{0}{1}",
                      values[ctr] != null ? values[ctr].Trim() : "",
                      ctr == values.GetUpperBound(0) ? "" : ", ");
    Console.WriteLine();
    
    // The example displays the following output:
    //       one, , two
    
    open System
    
    let values = [| "one"; null; "two" |]
    for i = 0 to values.GetUpperBound 0 do
        printf $"""{if values[i] <> null then values[i].Trim() else ""}{if i = values.GetUpperBound 0 then "" else ", "}"""
    Console.WriteLine()
    // The example displays the following output:
    //       one, , two
    
    Module Example
       Public Sub Main()
          Dim values() As String = { "one", Nothing, "two" }
          For ctr As Integer = 0 To values.GetUpperBound(0)
             Console.Write("{0}{1}", 
                           If(values(ctr) IsNot Nothing, values(ctr).Trim(), ""), 
                           If(ctr = values.GetUpperBound(0), "", ", ")) 
          Next
          Console.WriteLine()
       End Sub
    End Module
    ' The example displays the following output:
    '       one, , two
    
  • いずれかの引数のメンバーにアクセスするが、その引数が null場合のメソッド。 次の例の PopulateNames メソッドは、 names.Add(arrName);行で例外をスローします。

    using System.Collections.Generic;
    
    public class NRE2Example
    {
        public static void Main()
        {
            List<string> names = GetData();
            PopulateNames(names);
        }
    
        private static void PopulateNames(List<string> names)
        {
            string[] arrNames = [ "Dakota", "Samuel", "Nikita",
                                "Koani", "Saya", "Yiska", "Yumaevsky" ];
            foreach (string arrName in arrNames)
                names.Add(arrName);
        }
    
        private static List<string> GetData()
        {
            return null;
        }
    }
    
    // The example displays output like the following:
    //    Unhandled Exception: System.NullReferenceException: Object reference
    //    not set to an instance of an object.
    //       at NRE2Example.PopulateNames(List`1 names)
    //       at NRE2Example.Main()
    
    let populateNames (names: ResizeArray<string>) =
        let arrNames =
            [ "Dakota"; "Samuel"; "Nikita"
              "Koani"; "Saya"; "Yiska"; "Yumaevsky" ]
        for arrName in arrNames do
            names.Add arrName
    
    let getData () : ResizeArray<string> =
        null
    
    let names = getData ()
    populateNames names
    
    // The example displays output like the following:
    //    Unhandled Exception: System.NullReferenceException: Object reference
    //    not set to an instance of an object.
    //       at Example.PopulateNames(List`1 names)
    //       at <StartupCode$fs>.main()
    
    Imports System.Collections.Generic
    
    Module Example
       Public Sub Main()
          Dim names As List(Of String) = GetData()
          PopulateNames(names)
       End Sub
       
       Private Sub PopulateNames(names As List(Of String))
          Dim arrNames() As String = { "Dakota", "Samuel", "Nikita",
                                       "Koani", "Saya", "Yiska", "Yumaevsky" }
          For Each arrName In arrNames
             names.Add(arrName)
          Next
       End Sub
       
       Private Function GetData() As List(Of String)
          Return Nothing   
       End Function
    End Module
    ' The example displays output like the following:
    '    Unhandled Exception: System.NullReferenceException: Object reference 
    '    not set to an instance of an object.
    '       at Example.PopulateNames(List`1 names)
    '       at Example.Main()
    

    この問題に対処するには、メソッドに渡される引数が nullされていないことを確認するか、 try…catch…finally ブロックでスローされた例外を処理します。 詳細については、「 例外」を参照してください。

  • 型がわからない状態でリストが作成され、リストが初期化されませんでした。 次の例の GetList メソッドは、 emptyList.Add(value)行で例外をスローします。

    using System;
    using System.Collections.Generic;
    using System.Collections;
    using System.Runtime.Serialization;
    
    public class NullReferenceExample
    {
        public static void Main()
        {
            var listType = GetListType();
            _ = GetList(listType);
        }
    
        private static Type GetListType()
        {
            return typeof(List<int>);
        }
    
        private static IList GetList(Type type)
        {
            var emptyList = (IList)FormatterServices.GetUninitializedObject(type); // Does not call list constructor
            var value = 1;
            emptyList.Add(value);
            return emptyList;
        }
    }
    // The example displays output like the following:
    //    Unhandled Exception: System.NullReferenceException: 'Object reference
    //    not set to an instance of an object.'
    //    at System.Collections.Generic.List`1.System.Collections.IList.Add(Object item)
    //    at NullReferenceExample.GetList(Type type): line 24
    

    この問題に対処するには、リストが初期化されていることを確認するか (これを行う 1 つの方法は、FormatterServices.GetUninitializedObjectではなくActivator.CreateInstanceを呼び出す)、またはtry…catch…finally ブロックでスローされた例外を処理することです。 詳細については、「 例外」を参照してください。

次のMicrosoft中間言語 (MSIL) 命令は、NullReferenceException をスローします。callvirtcpblkcpobjinitblkldelem.<type>ldelemaldfldldfldaldind.<type>ldlenstelem.<type>stfldstind.<type>throw、および unbox

NullReferenceException では、値が0x80004003されている HRESULT COR_E_NULLREFERENCEが使用されます。

NullReferenceExceptionのインスタンスの初期プロパティ値の一覧については、NullReferenceExceptionコンストラクターを参照してください。

NullReferenceException 例外を処理するタイミング

通常、NullReferenceException は発生後に処理するよりも回避することをお勧めします。 例外を処理すると、コードの保守と理解が困難になり、他のバグが発生する場合があります。 NullReferenceException は、多くの場合、回復不可能なエラーです。 このような場合は、例外をアプリを停止することが最善の代替手段となる場合があります。

ただし、エラーの処理が役に立つ可能性がある状況は多数あります。

  • アプリは null のオブジェクトを無視できます。 たとえば、アプリがデータベース内のレコードを取得して処理する場合、null オブジェクトになるいくつかの不適切なレコードを無視できる場合があります。 悪いデータをログ ファイルまたはアプリケーション UI に記録すれば済む場合があります。

  • 例外から回復できます。 たとえば、参照型を返す Web サービスの呼び出しは、接続が失われたり、接続がタイムアウトした場合に null を返す場合があります。接続を再確立して、もう一度呼び出しを試みることができます。

  • アプリの状態を有効な状態に復元できます。 たとえば、NullReferenceException をスローするメソッドを呼び出す前に、データ ストアに情報を保存する必要があるマルチステップ タスクを実行する場合があります。 初期化されていないオブジェクトがデータ レコードを破損する場合は、アプリを閉じる前に前のデータを削除できます。

  • 例外を報告する必要があります。 たとえば、アプリのユーザーからの誤りによってエラーが発生した場合は、正しい情報を提供するのに役立つメッセージを生成できます。 エラーに関する情報をログに記録して、問題の解決に役立てることもできます。 ASP.NET などの一部のフレームワークには、アプリがクラッシュしないすべてのエラーをキャプチャする高度な例外ハンドラーがあります。その場合、例外が発生したことを知る唯一の方法は例外のログ記録である可能性があります。

コンストラクター

名前 説明
NullReferenceException()

NullReferenceException クラスの新しいインスタンスを初期化し、新しいインスタンスのMessage プロパティを、"オブジェクトのインスタンスが必要な場所で値 'null' が見つかりました" などのエラーを説明するシステム指定のメッセージに設定します。このメッセージでは、現在のシステム カルチャが考慮されます。

NullReferenceException(SerializationInfo, StreamingContext)
古い.

シリアル化されたデータを使用して、 NullReferenceException クラスの新しいインスタンスを初期化します。

NullReferenceException(String, Exception)

指定したエラー メッセージと、この例外の原因である内部例外への参照を使用して、 NullReferenceException クラスの新しいインスタンスを初期化します。

NullReferenceException(String)

指定したエラー メッセージを使用して、 NullReferenceException クラスの新しいインスタンスを初期化します。

プロパティ

名前 説明
Data

例外に関する追加のユーザー定義情報を提供するキーと値のペアのコレクションを取得します。

(継承元 Exception)
HelpLink

この例外に関連付けられているヘルプ ファイルへのリンクを取得または設定します。

(継承元 Exception)
HResult

特定の例外に割り当てられるコード化された数値である HRESULT を取得または設定します。

(継承元 Exception)
InnerException

現在の例外の原因となった Exception インスタンスを取得します。

(継承元 Exception)
Message

現在の例外を説明するメッセージを取得します。

(継承元 Exception)
Source

エラーの原因となるアプリケーションまたはオブジェクトの名前を取得または設定します。

(継承元 Exception)
StackTrace

呼び出し履歴のイミディエイト フレームの文字列表現を取得します。

(継承元 Exception)
TargetSite

現在の例外をスローするメソッドを取得します。

(継承元 Exception)

メソッド

名前 説明
Equals(Object)

指定されたオブジェクトが現在のオブジェクトと等しいかどうかを判断します。

(継承元 Object)
GetBaseException()

派生クラスでオーバーライドされた場合、1 つ以上の後続の例外の根本原因である Exception を返します。

(継承元 Exception)
GetHashCode()

既定のハッシュ関数として機能します。

(継承元 Object)
GetObjectData(SerializationInfo, StreamingContext)
古い.

派生クラスでオーバーライドされた場合は、例外に関する情報を使用して SerializationInfo を設定します。

(継承元 Exception)
GetType()

現在のインスタンスのランタイム型を取得します。

(継承元 Exception)
MemberwiseClone()

現在の Objectの簡易コピーを作成します。

(継承元 Object)
ToString()

現在の例外の文字列形式を作成して返します。

(継承元 Exception)

イベント

名前 説明
SerializeObjectState
古い.

例外に関するシリアル化されたデータを含む例外状態オブジェクトを作成するために例外がシリアル化されるときに発生します。

(継承元 Exception)

適用対象

こちらもご覧ください