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
屬性

備註

NullReferenceException當您嘗試在值為 null 的類型上存取成員時,會擲回例外狀況。 例外狀況 NullReferenceException 通常會反映開發人員錯誤,並在下列案例中擲回:

  • 您忘記具現化參考型別。 在下列範例中, names 宣告但永遠不會具現化:

    using System;
    using System.Collections.Generic;
    
    public class Example
    {
       public static void Main(string[] args)
       {
          int value = Int32.Parse(args[0]);
          List<String> names;
          if (value > 0)
             names = new List<String>();
    
          names.Add("Major Major Major");
       }
    }
    // Compilation displays a warning like the following:
    //    Example1.cs(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()
    
    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;
    using System.Collections.Generic;
    
    public class Example
    {
       public static void Main()
       {
          List<String> names = new List<String>();
          names.Add("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

    using System;
    
    public class Example
    {
       public static void Main()
       {
           int[] values = null;
           for (int ctr = 0; ctr <= 9; ctr++)
              values[ctr] = ctr * 2;
    
           foreach (var 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 Example.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()
    

    在初始化陣列之前,您可以宣告陣列中的元素數目,藉此消除例外狀況,如下列範例所示。

    using System;
    
    public class Example
    {
       public static void Main()
       {
           int[] values = new int[10];
           for (int ctr = 0; ctr <= 9; ctr++)
              values[ctr] = ctr * 2;
    
           foreach (var 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 方法一律會 Person 傳回其欄位符合搜尋字串的物件 FirstName 。 因為沒有相符專案,所以執行時間會 NullReferenceException 擲回例外狀況。

    using System;
    
    public class Example
    {
       public static void Main()
       {
          Person[] persons = Person.AddRange( new String[] { "Abigail", "Abra",
                                              "Abraham", "Adrian", "Ariella",
                                              "Arnold", "Aston", "Astor" } );
          String nameToFind = "Robert";
          Person found = Array.Find(persons, p => p.FirstName == nameToFind);
          Console.WriteLine(found.FirstName);
       }
    }
    
    public class Person
    {
       public static Person[] AddRange(String[] firstNames)
       {
          Person[] p = new Person[firstNames.Length];
          for (int ctr = 0; ctr < firstNames.Length; ctr++)
             p[ctr] = new Person(firstNames[ctr]);
    
          return p;
       }
    
       public Person(String firstName)
       {
          this.FirstName = firstName;
       }
    
       public String FirstName;
    }
    // The example displays the following output:
    //       Unhandled Exception: System.NullReferenceException:
    //       Object reference not set to an instance of an object.
    //          at Example.Main()
    
    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 在呼叫其任何成員之前,如下列範例所示。

    using System;
    
    public class Example
    {
       public static void Main()
       {
          Person[] persons = Person.AddRange( new String[] { "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("{0} not found.", nameToFind);
       }
    }
    
    public class Person
    {
       public static Person[] AddRange(String[] firstNames)
       {
          Person[] p = new Person[firstNames.Length];
          for (int ctr = 0; ctr < firstNames.Length; ctr++)
             p[ctr] = new Person(firstNames[ctr]);
    
          return p;
       }
    
       public Person(String firstName)
       {
          this.FirstName = firstName;
       }
    
       public String FirstName;
    }
    // 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 擲回例外狀況。 這是因為運算式中的其中一個中繼值會 null 傳回 。 因此,永遠不會評估您的 測試 null

    下列範例會 Pages 定義 物件,該物件會快取物件所 Page 呈現之網頁的相關資訊。 方法 Example.Main 會檢查目前的網頁是否有非 Null 標題,如果確實顯示標題,則為 。 不過,儘管這項檢查,此方法仍會擲回例外狀況 NullReferenceException

    using System;
    
    public class Example
    {
       public static void Main()
       {
          var pages = new Pages();
          if (! String.IsNullOrEmpty(pages.CurrentPage.Title)) {
             String title = pages.CurrentPage.Title;
             Console.WriteLine("Current title: '{0}'", title);
          }
       }
    }
    
    public class Pages
    {
       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] == 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 Example.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.CurrentPage 如果快取中沒有儲存任何頁面資訊,則會 null 傳回 。 藉由在擷取目前 Page 物件的 Title 屬性之前測試 屬性的值 CurrentPage ,即可更正此例外狀況,如下列範例所示:

    using System;
    
    public class Example
    {
       public static void Main()
       {
          var pages = new Pages();
          Page current = pages.CurrentPage;
          if (current != null) {
             String title = current.Title;
             Console.WriteLine("Current title: '{0}'", 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 方法。

    using System;
    
    public class Example
    {
       public static void Main()
       {
          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.
    //       at Example.Main()
    
    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 是否在對該專案執行任何作業之前,來排除例外狀況,如下列範例所示。

    using System;
    
    public class Example
    {
       public static void Main()
       {
          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
    
  • NullReferenceException方法存取其中一個引數的成員時,可能會擲回例外狀況,但該引數為 nullPopulateNames下列範例中的 方法會在 行 names.Add(arrName); 擲回例外狀況。

    using System;
    using System.Collections.Generic;
    
    public class Example
    {
       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 (var 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 Example.PopulateNames(List`1 names)
    //       at Example.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 例外狀況。 如需詳細資訊,請參閱 例外狀況中定義的介面的私用 C++ 專屬實作。

下列 Microsoft 中繼語言 (MSIL) 指令擲回 NullReferenceExceptioncallvirtcpblkinitblkldfldldfldaldelemaldind.<type>ldlenldelem.<type>cpobjstfldstind.<type>stelem.<type>throw 和 。 unbox

NullReferenceException 會使用 HRESULT COR_E_NullREFERENCE,其值為 0x80004003。

如需執行個體的初始屬性值的清單NullReferenceException,請參閱NullReferenceException建構函式。

處理發行程式碼中的 NullReferenceException

通常最好避免 NullReferenceException,而不是在發生之後處理它。 處理例外狀況會讓您的程式碼更難維護及了解,而且有時候會引進其他 Bug。 NullReferenceException 通常是無法修復的錯誤。 在這些案例中,讓例外狀況停止應用程式可能是最好的替代方案。

不過,有許多情況中處理錯誤會有幫助。

  • 您的應用程式可以忽略 null 的物件。 例如,如果您的應用程式會擷取並處理資料庫中的記錄,也許您可以忽略某些會產生 null 物件的錯誤記錄。 將錯誤資料記錄在記錄檔或應用程式 UI 中可能是您唯一必須做的事。

  • 您可以從例外狀況復原。 例如,如果連線遺失或連接逾時,傳回參考類型的 Web 服務呼叫可能會傳回 null。您可以嘗試重新建立連線,然後再試一次呼叫。

  • 您可以將應用程式的狀態還原至有效狀態。 例如,您執行的多步驟工作可能會需要您先將資訊儲存至資料儲存區,才能呼叫擲回 NullReferenceException 的方法。 如果未初始化的物件會損毀資料記錄,您可以先移除之前的資料再關閉應用程式。

  • 您想要回報該例外狀況。 例如,如果錯誤是由您應用程式使用者的錯誤所造成,您可以產生訊息來協助他們提供正確的資訊。 您也可以記錄錯誤的資訊,以幫助您修正問題。 有些架構,像 ASP.NET,具有高層級且可以擷取所有錯誤的例外狀況處理常式,此時應用程式永遠不會損毀,在這種情況下,記錄例外狀況可能是您可以知道它有發生的唯一方法。

建構函式

NullReferenceException()

初始化 類別的新實例,並將新實例 NullReferenceException 的 屬性設定 Message 為描述錯誤的系統提供的訊息,例如「找到需要物件實例的值 'null'」。此訊息會將目前的系統文化特性納入考慮。

NullReferenceException(SerializationInfo, StreamingContext)
已淘汰.

使用序列化資料,初始化 NullReferenceException 類別的新執行個體。

NullReferenceException(String)

使用指定的錯誤訊息,初始化 NullReferenceException 類別的新執行個體。

NullReferenceException(String, Exception)

使用指定的錯誤訊息以及造成此例外狀況的內部例外狀況的參考,初始化 NullReferenceException 類別的新執行個體。

屬性

Data

取得鍵值組的集合,這些鍵值組會提供關於例外狀況的其他使用者定義資訊。

(繼承來源 Exception)
HelpLink

取得或設定與這個例外狀況相關聯的說明檔連結。

(繼承來源 Exception)
HResult

取得或設定 HRESULT,它是指派給特定例外狀況的編碼數值。

(繼承來源 Exception)
InnerException

取得造成目前例外狀況的 Exception 執行個體。

(繼承來源 Exception)
Message

取得描述目前例外狀況的訊息。

(繼承來源 Exception)
Source

取得或設定造成錯誤的應用程式或物件的名稱。

(繼承來源 Exception)
StackTrace

取得呼叫堆疊上即時運算框架的字串表示。

(繼承來源 Exception)
TargetSite

取得擲回目前例外狀況的方法。

(繼承來源 Exception)

方法

Equals(Object)

判斷指定的物件是否等於目前的物件。

(繼承來源 Object)
GetBaseException()

在衍生類別中覆寫時,傳回一或多個後續的例外狀況的根本原因 Exception

(繼承來源 Exception)
GetHashCode()

做為預設雜湊函式。

(繼承來源 Object)
GetObjectData(SerializationInfo, StreamingContext)
已淘汰.

在衍生類別中覆寫時,使用例外狀況的資訊設定 SerializationInfo

(繼承來源 Exception)
GetType()

取得目前執行個體的執行階段類型。

(繼承來源 Exception)
MemberwiseClone()

建立目前 Object 的淺層複製。

(繼承來源 Object)
ToString()

建立並傳回目前例外狀況的字串表示。

(繼承來源 Exception)

事件

SerializeObjectState
已淘汰.

當例外狀況序列化,以建立包含例外狀況相關序列化資料的例外狀況狀態物件時,就會發生此事件。

(繼承來源 Exception)

適用於

另請參閱