NullReferenceException 클래스

정의

null 개체 참조를 역참조하려고 할 때 throw되는 예외입니다.

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 값이 있는 형식의 멤버에 액세스하려고 하면 예외가 throw됩니다null. 예외는 NullReferenceException 일반적으로 개발자 오류를 반영하며 다음 시나리오에서 throw됩니다.

메모

null 조건부 연산자() 또는 null 병합 연산자(?.)를 사용하여 C#에서 대부분의 NullReferenceException 예외?? 방지할 수 있습니다. 더 많은 정보를 보려면 nullable 참조 유형을 참조하세요. 다음 C# 예제에서는 nullable 컨텍스트가 사용하지 않도록 설정되어 있다고 가정합니다(권장되지 않음).

  • 참조 형식을 인스턴스화하는 것을 잊어버렸습니다. 다음 예제 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 throw됩니다.

    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 throw합니다.

    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 throw합니다. 식의 중간 값 중 하나가 반환되므로 발생합니다 null. 따라서 테스트 null 는 평가되지 않습니다.

    다음 예제에서는 개체에서 Pages 제공하는 웹 페이지에 대한 정보를 캐시하는 개체를 Page 정의합니다. 이 메서드는 Example.Main 현재 웹 페이지에 null이 아닌 제목이 있는지 확인하고, null이 아닌 경우 제목을 표시합니다. 그러나 이 검사에도 불구하고 메서드는 예외를 NullReferenceException throw합니다.

    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()
    

    캐시에 페이지 정보가 저장되지 않은 경우 반환 null 되므로 예외가 throw pages.CurrentPage 됩니다. 다음 예제와 같이 현재 Page 개체 TitleCurrentPage 속성을 검색하기 전에 속성 값을 테스트하여 이 예외를 수정할 수 있습니다.

    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 throw됩니다.

    다음 예제에서는 문자열 배열을 정의합니다. 문은 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. 다음 예제의 메서드는 PopulateNamesnames.Add(arrName);에 예외를 throw합니다.

    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확인하거나 블록에서 throw된 예외를 try…catch…finally 처리합니다. 자세한 내용은 예외를 참조하세요.

  • 형식을 모르고 목록이 만들어지고 목록이 초기화되지 않았습니다. 다음 예제의 메서드는 GetListemptyList.Add(value)에 예외를 throw합니다.

    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
    

    이 문제를 해결하려면 목록이 초기화되어 있는지 확인합니다(이 작업을 수행하는 한 가지 방법은 대신 FormatterServices.GetUninitializedObject호출 Activator.CreateInstance 하는 것입니다). 또는 블록에서 throw된 예외를 try…catch…finally 처리합니다. 자세한 내용은 예외를 참조하세요.

MSIL(Microsoft 중간 언어) 명령은 NullReferenceException throw합니다. callvirtcpblk, cpobj, initblk, ldelem.<type>, ldelema, ldfld, ldfldaldind.<type>, ldlen, stelem.<type>, stfld, stind.<type>, throwunbox.

NullReferenceException 는 값이 0x80004003 HRESULT COR_E_NULLREFERENCE를 사용합니다.

NullReferenceException인스턴스의 초기 속성 값 목록은 NullReferenceException 생성자를 참조하세요.

NullReferenceException 예외를 처리해야 하는 경우

NullReferenceException이 발생한 후 처리하는 것보다 일반적으로 NullReferenceException을 방지하는 것이 좋습니다. 예외를 처리하면 코드를 유지 관리하고 이해하기 어렵게 만들 수 있으며 때로는 다른 버그가 발생할 수 있습니다. NullReferenceException은 종종 복구할 수 없는 오류입니다. 이러한 경우 예외가 앱을 중지하도록 하는 것이 가장 좋은 대안일 수 있습니다.

그러나 오류를 처리하는 것이 유용할 수 있는 많은 상황이 있습니다.

  • 앱은 null인 개체를 무시할 수 있습니다. 예를 들어 앱이 데이터베이스의 레코드를 검색하고 처리하는 경우 null 개체를 생성하는 몇 가지 잘못된 레코드를 무시할 수 있습니다. 로그 파일 또는 애플리케이션 UI에서 잘못된 데이터를 기록하는 것이 전부일 수 있습니다.

  • 예외에서 복구할 수 있습니다. 예를 들어 연결이 끊어지거나 연결 시간이 초과되면 참조 형식을 반환하는 웹 서비스에 대한 호출이 null을 반환할 수 있습니다. 연결을 다시 설정하여 호출을 다시 시도할 수 있습니다.

  • 앱의 상태를 유효한 상태로 복원할 수 있습니다. 예를 들어 NullReferenceException을 throw하는 메서드를 호출하기 전에 데이터 저장소에 정보를 저장해야 하는 다단계 작업을 수행할 수 있습니다. 초기화되지 않은 개체가 데이터 레코드를 손상하는 경우 앱을 닫기 전에 이전 데이터를 제거할 수 있습니다.

  • 예외를 보고하려고 합니다. 예를 들어 앱 사용자의 실수로 인해 오류가 발생한 경우 올바른 정보를 제공하는 데 도움이 되는 메시지를 생성할 수 있습니다. 오류에 대한 정보를 기록하여 문제를 해결하는 데 도움이 될 수도 있습니다. ASP.NET 같은 일부 프레임워크에는 앱이 충돌하지 않는 모든 오류를 캡처하는 상위 수준 예외 처리기가 있습니다. 이 경우 예외가 발생한다는 것을 알 수 있는 유일한 방법일 수 있습니다.

생성자

Name Description
NullReferenceException()

클래스의 NullReferenceException 새 인스턴스를 초기화하고 새 인스턴스의 속성을 "개체 인스턴스가 필요한 경우 'null' 값을 찾았습니다."와 같이 오류를 설명하는 시스템 제공 메시지로 설정합니다 Message . 이 메시지는 현재 시스템 문화권을 고려합니다.

NullReferenceException(SerializationInfo, StreamingContext)
사용되지 않음.

직렬화된 데이터를 사용하여 클래스의 새 인스턴스를 NullReferenceException 초기화합니다.

NullReferenceException(String, Exception)

지정된 오류 메시지와 이 예외의 NullReferenceException 원인인 내부 예외에 대한 참조를 사용하여 클래스의 새 인스턴스를 초기화합니다.

NullReferenceException(String)

지정된 오류 메시지를 사용하여 클래스의 NullReferenceException 새 인스턴스를 초기화합니다.

속성

Name Description
Data

예외에 대한 추가 사용자 정의 정보를 제공하는 키/값 쌍의 컬렉션을 가져옵니다.

(다음에서 상속됨 Exception)
HelpLink

이 예외와 연결된 도움말 파일에 대한 링크를 가져오거나 설정합니다.

(다음에서 상속됨 Exception)
HResult

특정 예외에 할당된 코딩된 숫자 값인 HRESULT를 가져오거나 설정합니다.

(다음에서 상속됨 Exception)
InnerException

현재 예외를 Exception 발생시킨 인스턴스를 가져옵니다.

(다음에서 상속됨 Exception)
Message

현재 예외를 설명하는 메시지를 가져옵니다.

(다음에서 상속됨 Exception)
Source

오류를 발생시키는 애플리케이션 또는 개체의 이름을 가져오거나 설정합니다.

(다음에서 상속됨 Exception)
StackTrace

호출 스택에서 직접 실행 프레임의 문자열 표현을 가져옵니다.

(다음에서 상속됨 Exception)
TargetSite

현재 예외를 throw하는 메서드를 가져옵니다.

(다음에서 상속됨 Exception)

메서드

Name Description
Equals(Object)

지정된 개체가 현재 개체와 같은지 여부를 확인합니다.

(다음에서 상속됨 Object)
GetBaseException()

파생 클래스에서 재정의되는 경우 하나 이상의 후속 예외의 근본 원인인 값을 반환 Exception 합니다.

(다음에서 상속됨 Exception)
GetHashCode()

기본 해시 함수로 사용됩니다.

(다음에서 상속됨 Object)
GetObjectData(SerializationInfo, StreamingContext)
사용되지 않음.

파생 클래스에서 재정의되는 경우 예외에 SerializationInfo 대한 정보를 사용하여 설정합니다.

(다음에서 상속됨 Exception)
GetType()

현재 인스턴스의 런타임 형식을 가져옵니다.

(다음에서 상속됨 Exception)
MemberwiseClone()

현재 Object단순 복사본을 만듭니다.

(다음에서 상속됨 Object)
ToString()

현재 예외의 문자열 표현을 만들고 반환합니다.

(다음에서 상속됨 Exception)

이벤트

Name Description
SerializeObjectState
사용되지 않음.

예외에 대한 직렬화된 데이터를 포함하는 예외 상태 개체를 만들기 위해 예외가 serialize될 때 발생합니다.

(다음에서 상속됨 Exception)

적용 대상

추가 정보