NullReferenceException Klasa
Definicja
Ważne
Niektóre informacje odnoszą się do produktu w wersji wstępnej, który może zostać znacząco zmodyfikowany przed wydaniem. Firma Microsoft nie udziela żadnych gwarancji, jawnych lub domniemanych, w odniesieniu do informacji podanych w tym miejscu.
Wyjątek zgłaszany podczas próby wyłudzenia odwołania do obiektu o wartości 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
- Dziedziczenie
- Dziedziczenie
- Atrybuty
Uwagi
Podczas NullReferenceException próby uzyskania dostępu do elementu członkowskiego w typie, którego wartość to null. Wyjątek NullReferenceException zwykle odzwierciedla błąd dewelopera i jest zgłaszany w następujących scenariuszach:
Uwaga / Notatka
Większość wyjątków w języku C# można uniknąć NullReferenceException , używając operatora warunkowego o wartości null (?.) lub operatora łączenia wartości null (??). Aby uzyskać więcej informacji, zobacz Typy referencyjne dopuszczane do wartości null. W poniższych przykładach w języku C# założono, że kontekst dopuszczalny do wartości null jest wyłączony (niezalecane).
Nie pamiętasz o utworzeniu wystąpienia typu odwołania. W poniższym przykładzie jest deklarowany,
namesale nigdy nie tworzy wystąpienia (wiersz, którego dotyczy problem, jest komentowany w przykładzie języka C#, ponieważ nie jest kompilowany):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()Niektóre kompilatory wydają ostrzeżenie podczas kompilowania tego kodu. Inne wystawiają błąd, a kompilacja kończy się niepowodzeniem. Aby rozwiązać ten problem, utwórz wystąpienie obiektu, aby jego wartość nie
nullprzekraczała wartości . W poniższym przykładzie jest to spowodowane wywołaniem konstruktora klasy typu.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 ModuleNie pamiętasz wymiarowania tablicy przed jej zainicjowaniem. W poniższym przykładzie
valuesjest zadeklarowana jako tablica całkowita, ale liczba elementów, które zawiera, nigdy nie jest określona. Próba zainicjowania jej wartości zwraca NullReferenceException zatem wyjątek.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()Wyjątek można wyeliminować, deklarując liczbę elementów w tablicy przed jej zainicjowaniem, jak w poniższym przykładzie.
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 // 18let 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 // 18Module 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 ' 18Aby uzyskać więcej informacji na temat deklarowania i inicjowania tablic, zobacz Tablice i tablice.
Otrzymasz wartość zwracaną o wartości null z metody, a następnie wywołaj metodę dla zwracanego typu. Czasami jest to wynik błędu dokumentacji; Nie można zauważyć, że wywołanie metody może zwrócić
nullwartość . W innych przypadkach kod błędnie zakłada, że metoda zawsze zwróci wartość inną niż null.W poniższym przykładzie przyjęto założenie, że Array.Find metoda zawsze zwraca
Personobiekt, któregoFirstNamepole pasuje do ciągu wyszukiwania. Ponieważ nie ma dopasowania, środowisko uruchomieniowe zgłasza NullReferenceException wyjątek.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()Aby rozwiązać ten problem, przetestuj wartość zwracaną metody, aby upewnić się, że nie
nulljest ona przed wywołaniem żadnego z jego elementów członkowskich, jak to robi poniższy przykład.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 foundopen 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 foundUżywasz wyrażenia (na przykład połączono listę metod lub właściwości) w celu pobrania wartości i, mimo że sprawdzasz, czy wartość to
null, środowisko uruchomieniowe nadal zgłasza NullReferenceException wyjątek. Dzieje się tak, ponieważ jedna z wartości pośrednich w wyrażeniu zwraca wartośćnull. W rezultacie test dlanullelementu nigdy nie zostanie oceniony.W poniższym przykładzie zdefiniowano
Pagesobiekt, który buforuje informacje o stronach sieci Web, które są prezentowane przezPageobiekty. MetodaExample.Mainsprawdza, czy bieżąca strona internetowa ma tytuł inny niż null, a jeśli tak, wyświetla tytuł. Pomimo tego sprawdzenia metoda zgłasza NullReferenceException jednak wyjątek.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()Wyjątek jest zgłaszany, ponieważ
pages.CurrentPagezwraca wartość ,nulljeśli żadne informacje o stronie nie są przechowywane w pamięci podręcznej. Ten wyjątek można poprawić, testując wartośćCurrentPagewłaściwości przed pobraniem właściwości bieżącegoPageobiektuTitle, jak w poniższym przykładzie: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.Wyliczasz elementy tablicy zawierającej typy odwołań, a próba przetworzenia jednego z elementów zgłasza NullReferenceException wyjątek.
W poniższym przykładzie zdefiniowano tablicę ciągów. Instrukcja
forwylicza elementy w tablicy i wywołuje metodę każdego ciągu Trim przed wyświetleniem ciągu.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()Ten wyjątek występuje, jeśli zakładasz, że każdy element tablicy musi zawierać wartość inną niż null, a wartość elementu tablicy jest w rzeczywistości
null. Wyjątek można wyeliminować, testując, czy element znajduje sięnullprzed wykonaniem dowolnej operacji na tym elemecie, jak pokazano w poniższym przykładzie.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, , twoopen 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, , twoModule 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, , twoMetoda, gdy uzyskuje dostęp do elementu członkowskiego jednego z jego argumentów, ale argumentem jest
null. MetodaPopulateNamesw poniższym przykładzie zgłasza wyjątek w wierszunames.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()Aby rozwiązać ten problem, upewnij się, że argument przekazany do metody nie
nullma wartości , lub obsłuż wyjątek zgłoszony wtry…catch…finallybloku. Aby uzyskać więcej informacji, zobacz Wyjątki.Lista jest tworzona bez znajomości typu, a lista nie została zainicjowana. Metoda
GetListw poniższym przykładzie zgłasza wyjątek w wierszuemptyList.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 24Aby rozwiązać ten problem, upewnij się, że lista została zainicjowana (jednym ze sposobów wykonania tej czynności jest wywołanie
Activator.CreateInstancezamiastFormatterServices.GetUninitializedObject), lub obsłuż wyjątek zgłoszony wtry…catch…finallybloku. Aby uzyskać więcej informacji, zobacz Wyjątki.
Następujące instrukcje dotyczące języka Microsoft pośredniego (MSIL) zgłaszają NullReferenceException: callvirt, cpblk, cpobj, initblk, ldelem.<type>, ldelema, ldfld, ldflda, ldind.<type>, ldlen, stelem.<type>, stfld, stind.<type>, throw i unbox.
NullReferenceException używa wartości HRESULT COR_E_NULLREFERENCE, która ma wartość 0x80004003.
Aby uzyskać listę początkowych wartości właściwości dla wystąpienia NullReferenceException, zapoznaj się z konstruktorami NullReferenceException.
Kiedy obsługiwać wyjątki NullReferenceException
Zwykle lepiej jest uniknąć błędu NullReferenceException niż obsługiwać go po jego wystąpieniu. Obsługa wyjątku może utrudnić konserwację i zrozumienie kodu, a czasami wprowadzać inne błędy. Wyjątek NullReferenceException jest często błędem niemożliwym do odzyskania. W takich przypadkach zezwolenie na zatrzymanie wyjątku aplikacji może być najlepszą alternatywą.
Istnieje jednak wiele sytuacji, w których obsługa błędu może być przydatna:
Aplikacja może ignorować obiekty, które mają wartość null. Jeśli na przykład aplikacja pobiera i przetwarza rekordy w bazie danych, może być możliwe zignorowanie pewnej liczby nieprawidłowych rekordów, które powodują powstanie obiektów null. Rejestrowanie nieprawidłowych danych w pliku dziennika lub w interfejsie użytkownika aplikacji może być wszystko, co musisz zrobić.
Możesz odzyskać dane z wyjątku. Na przykład wywołanie usługi internetowej zwracającej typ odwołania może zwrócić wartość null, jeśli połączenie zostanie utracone lub przekroczono limit czasu połączenia. Możesz spróbować ponownie opublikować połączenie i ponowić próbę wywołania.
Stan aplikacji można przywrócić do prawidłowego stanu. Na przykład możesz wykonać wieloetapowe zadanie, które wymaga zapisania informacji w magazynie danych przed wywołaniem metody, która zgłasza wyjątek NullReferenceException. Jeśli niezainicjowany obiekt uszkodzi rekord danych, możesz usunąć poprzednie dane przed zamknięciem aplikacji.
Chcesz zgłosić wyjątek. Jeśli na przykład błąd został spowodowany przez pomyłkę użytkownika aplikacji, możesz wygenerować komunikat, aby pomóc im podać poprawne informacje. Możesz również rejestrować informacje o błędzie, aby ułatwić rozwiązanie problemu. Niektóre struktury, takie jak ASP.NET, mają procedurę obsługi wyjątków wysokiego poziomu, która przechwytuje wszystkie błędy, których aplikacja nigdy nie ulega awarii. W takim przypadku rejestrowanie wyjątku może być jedynym sposobem, w jaki można wiedzieć, że występuje.
Konstruktory
| Nazwa | Opis |
|---|---|
| NullReferenceException() |
Inicjuje nowe wystąpienie NullReferenceException klasy, ustawiając Message właściwość nowego wystąpienia na komunikat dostarczony przez system, który opisuje błąd, taki jak "Wartość null" została znaleziona, gdy wymagane było wystąpienie obiektu. Ten komunikat uwzględnia bieżącą kulturę systemu. |
| NullReferenceException(SerializationInfo, StreamingContext) |
Przestarzałe.
Inicjuje NullReferenceException nowe wystąpienie klasy z serializowanymi danymi. |
| NullReferenceException(String, Exception) |
Inicjuje nowe wystąpienie NullReferenceException klasy z określonym komunikatem o błędzie i odwołaniem do wyjątku wewnętrznego, który jest przyczyną tego wyjątku. |
| NullReferenceException(String) |
Inicjuje nowe wystąpienie klasy NullReferenceException z określonym komunikatem o błędzie. |
Właściwości
| Nazwa | Opis |
|---|---|
| Data |
Pobiera kolekcję par klucz/wartość, które zapewniają dodatkowe informacje zdefiniowane przez użytkownika dotyczące wyjątku. (Odziedziczone po Exception) |
| HelpLink |
Pobiera lub ustawia link do pliku pomocy skojarzonego z tym wyjątkiem. (Odziedziczone po Exception) |
| HResult |
Pobiera lub ustawia HRESULT, zakodowaną wartość liczbową przypisaną do określonego wyjątku. (Odziedziczone po Exception) |
| InnerException |
Exception Pobiera wystąpienie, które spowodowało bieżący wyjątek. (Odziedziczone po Exception) |
| Message |
Pobiera komunikat opisujący bieżący wyjątek. (Odziedziczone po Exception) |
| Source |
Pobiera lub ustawia nazwę aplikacji lub obiektu, który powoduje błąd. (Odziedziczone po Exception) |
| StackTrace |
Pobiera reprezentację ciągu natychmiastowych ramek na stosie wywołań. (Odziedziczone po Exception) |
| TargetSite |
Pobiera metodę, która zgłasza bieżący wyjątek. (Odziedziczone po Exception) |
Metody
| Nazwa | Opis |
|---|---|
| Equals(Object) |
Określa, czy określony obiekt jest równy bieżącemu obiektowi. (Odziedziczone po Object) |
| GetBaseException() |
Po zastąpieniu w klasie pochodnej funkcja zwraca Exception główną przyczynę co najmniej jednego kolejnego wyjątku. (Odziedziczone po Exception) |
| GetHashCode() |
Służy jako domyślna funkcja skrótu. (Odziedziczone po Object) |
| GetObjectData(SerializationInfo, StreamingContext) |
Przestarzałe.
Po przesłonięciu w klasie pochodnej ustawia element SerializationInfo z informacjami o wyjątku. (Odziedziczone po Exception) |
| GetType() |
Pobiera typ środowiska uruchomieniowego bieżącego wystąpienia. (Odziedziczone po Exception) |
| MemberwiseClone() |
Tworzy płytkią kopię bieżącego Object. (Odziedziczone po Object) |
| ToString() |
Tworzy i zwraca reprezentację ciągu bieżącego wyjątku. (Odziedziczone po Exception) |
Zdarzenia
| Nazwa | Opis |
|---|---|
| SerializeObjectState |
Przestarzałe.
Występuje, gdy wyjątek jest serializowany w celu utworzenia obiektu stanu wyjątku zawierającego serializowane dane dotyczące wyjątku. (Odziedziczone po Exception) |