NullReferenceException Classe
Definição
Importante
Algumas informações se referem a produtos de pré-lançamento que podem ser substancialmente modificados antes do lançamento. A Microsoft não oferece garantias, expressas ou implícitas, das informações aqui fornecidas.
A exceção gerada quando há uma tentativa de desreferenciar uma referência de objeto nulo.
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
- Herança
- Herança
- Atributos
Comentários
Uma NullReferenceException exceção é gerada quando você tenta acessar um membro em um tipo cujo valor é null. Uma NullReferenceException exceção normalmente reflete o erro do desenvolvedor e é gerada nos seguintes cenários:
Note
Você pode evitar a maioria NullReferenceException das exceções em C# usando o operador condicional nulo (?.) ou o operador de coalescing nulo (??). Para obter mais informações, confira Tipos de referência anuláveis. Os exemplos de C# a seguir pressupõem que o contexto anulável está desabilitado (não recomendado).
Você esqueceu de criar uma instância de um tipo de referência. No exemplo a seguir, é declarado,
namesmas nunca instanciado (a linha afetada é comentada no exemplo C#, pois não compila):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()Alguns compiladores emitem um aviso ao compilar esse código. Outros emitem um erro e a compilação falha. Para resolver esse problema, instancie o objeto para que seu valor não seja mais
null. O exemplo a seguir faz isso chamando o construtor de classe de um tipo.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 ModuleVocê esqueceu de dimensionar uma matriz antes de inicializá-la. No exemplo a seguir,
valuesé declarado como uma matriz de inteiros, mas o número de elementos que ele contém nunca é especificado. A tentativa de inicializar seus valores gera, portanto, uma NullReferenceException exceção.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()Você pode eliminar a exceção declarando o número de elementos na matriz antes de inicializá-la, como o exemplo a seguir faz.
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 ' 18Para obter mais informações sobre como declarar e inicializar matrizes, consulte Matrizes e Matrizes.
Você obtém um valor retornado nulo de um método e, em seguida, chama um método no tipo retornado. Às vezes, isso é o resultado de um erro de documentação; a documentação não observa que uma chamada de método pode retornar
null. Em outros casos, seu código assume erroneamente que o método sempre retornará um valor não nulo.O código no exemplo a seguir pressupõe que o Array.Find método sempre retorna
Personum objeto cujoFirstNamecampo corresponde a uma cadeia de caracteres de pesquisa. Como não há correspondência, o runtime gera uma NullReferenceException exceção.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()Para resolver esse problema, teste o valor retornado do método para garantir que ele não
nullesteja antes de chamar nenhum de seus membros, como o exemplo a seguir faz.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 foundVocê está usando uma expressão (por exemplo, encadeou uma lista de métodos ou propriedades juntos) para recuperar um valor e, embora esteja verificando se o valor é
null, o runtime ainda gera uma NullReferenceException exceção. Isso ocorre porque um dos valores intermediários na expressão retornanull. Como resultado, seu testenullnunca é avaliado.O exemplo a seguir define um
Pagesobjeto que armazena em cache informações sobre páginas da Web, que são apresentadas porPageobjetos. OExample.Mainmétodo verifica se a página da Web atual tem um título não nulo e, se o fizer, exibe o título. No entanto, apesar dessa verificação, o método gera uma NullReferenceException exceção.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()A exceção é gerada porque
pages.CurrentPageretornanullse nenhuma informação de página é armazenada no cache. Essa exceção pode ser corrigida testando o valor da propriedade antes deCurrentPagerecuperar a propriedade doTitleobjeto atualPage, como o exemplo a seguir: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.Você está enumerando os elementos de uma matriz que contém tipos de referência e sua tentativa de processar um dos elementos gera uma NullReferenceException exceção.
O exemplo a seguir define uma matriz de cadeia de caracteres. Uma
forinstrução enumera os elementos na matriz e chama o método de Trim cada cadeia de caracteres antes de exibir a cadeia de caracteres.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()Essa exceção ocorre se você pressupõe que cada elemento da matriz deve conter um valor não nulo e o valor do elemento de matriz é de fato
null. A exceção pode ser eliminada testando se o elemento estánullantes de executar qualquer operação nesse elemento, como mostra o exemplo a seguir.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, , twoUm método quando ele acessa um membro de um de seus argumentos, mas esse argumento é
null. OPopulateNamesmétodo no exemplo a seguir gera a exceção na linhanames.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()Para resolver esse problema, verifique se o argumento passado para o método não
nullestá ou manipule a exceção gerada em umtry…catch…finallybloco. Para obter mais informações, consulte Exceções.Uma lista é criada sem saber o tipo e a lista não foi inicializada. O
GetListmétodo no exemplo a seguir gera a exceção na linhaemptyList.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 24Para resolver esse problema, verifique se a lista está inicializada (uma maneira de fazer isso é chamar
Activator.CreateInstanceem vez deFormatterServices.GetUninitializedObject) ou manipular a exceção gerada em umtry…catch…finallybloco. Para obter mais informações, consulte Exceções.
As seguintes instruções Microsoft linguagem intermediária (MSIL) lançam NullReferenceException: callvirt, cpblk, cpobj, initblk, ldelem.<type>, ldelema, ldfld, ldflda, ldind.<type>, ldlen, stelem.<type>, stfld, stind.<type>, throw e unbox.
NullReferenceException usa o HRESULT COR_E_NULLREFERENCE, que tem o valor 0x80004003.
Para obter uma lista de valores de propriedade iniciais de uma instância de NullReferenceException, consulte os construtores de NullReferenceException.
Quando lidar com exceções NullReferenceException
Geralmente, é melhor evitar uma NullReferenceException do que lidar com ela depois que ela ocorrer. Lidar com uma exceção pode dificultar a manutenção e a compreensão do código e, às vezes, pode introduzir outros bugs. Um NullReferenceException geralmente é um erro não recuperável. Nesses casos, permitir que a exceção interrompa o aplicativo pode ser a melhor alternativa.
No entanto, há muitas situações em que lidar com o erro pode ser útil:
Seu aplicativo pode ignorar objetos que são nulos. Por exemplo, se seu aplicativo recuperar e processar registros em um banco de dados, você poderá ignorar alguns registros inválidos que resultam em objetos nulos. Gravar os dados incorretos em um arquivo de log ou na interface do usuário do aplicativo pode ser tudo o que você precisa fazer.
Você pode se recuperar da exceção. Por exemplo, uma chamada para um serviço Web que retorna um tipo de referência pode retornar nulo se a conexão for perdida ou a conexão atingir o tempo limite. Você pode tentar restabelecer a conexão e tentar a chamada novamente.
Você pode restaurar o estado do aplicativo para um estado válido. Por exemplo, você pode estar executando uma tarefa de várias etapas que exige que você salve informações em um armazenamento de dados antes de chamar um método que gera um NullReferenceException. Se o objeto não inicializado corromper o registro de dados, você poderá remover os dados anteriores antes de fechar o aplicativo.
Você deseja relatar a exceção. Por exemplo, se o erro foi causado por um erro do usuário do seu aplicativo, você pode gerar uma mensagem para ajudá-lo a fornecer as informações corretas. Você também pode registrar informações sobre o erro para ajudá-lo a corrigir o problema. Algumas estruturas, como ASP.NET, têm um manipulador de exceção de alto nível que captura todos os erros para que o aplicativo nunca falhe; nesse caso, registrar a exceção pode ser a única maneira de saber que ela ocorre.
Construtores
| Nome | Description |
|---|---|
| NullReferenceException() |
Inicializa uma nova instância da NullReferenceException classe, definindo a Message propriedade da nova instância como uma mensagem fornecida pelo sistema que descreve o erro, como "O valor 'null' foi encontrado onde uma instância de um objeto era necessária." Essa mensagem leva em conta a cultura atual do sistema. |
| NullReferenceException(SerializationInfo, StreamingContext) |
Obsoleto.
Inicializa uma nova instância da NullReferenceException classe com dados serializados. |
| NullReferenceException(String, Exception) |
Inicializa uma nova instância da NullReferenceException classe com uma mensagem de erro especificada e uma referência à exceção interna que é a causa dessa exceção. |
| NullReferenceException(String) |
Inicializa uma nova instância da classe NullReferenceException com uma mensagem de erro especificada. |
Propriedades
| Nome | Description |
|---|---|
| Data |
Obtém uma coleção de pares chave/valor que fornecem informações adicionais definidas pelo usuário sobre a exceção. (Herdado de Exception) |
| HelpLink |
Obtém ou define um link para o arquivo de ajuda associado a essa exceção. (Herdado de Exception) |
| HResult |
Obtém ou define HRESULT, um valor numérico codificado atribuído a uma exceção específica. (Herdado de Exception) |
| InnerException |
Obtém a Exception instância que causou a exceção atual. (Herdado de Exception) |
| Message |
Obtém uma mensagem que descreve a exceção atual. (Herdado de Exception) |
| Source |
Obtém ou define o nome do aplicativo ou do objeto que causa o erro. (Herdado de Exception) |
| StackTrace |
Obtém uma representação de cadeia de caracteres dos quadros imediatos na pilha de chamadas. (Herdado de Exception) |
| TargetSite |
Obtém o método que gera a exceção atual. (Herdado de Exception) |
Métodos
| Nome | Description |
|---|---|
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual. (Herdado de Object) |
| GetBaseException() |
Quando substituído em uma classe derivada, retorna a Exception causa raiz de uma ou mais exceções subsequentes. (Herdado de Exception) |
| GetHashCode() |
Serve como a função de hash padrão. (Herdado de Object) |
| GetObjectData(SerializationInfo, StreamingContext) |
Obsoleto.
Quando substituído em uma classe derivada, define o SerializationInfo com informações sobre a exceção. (Herdado de Exception) |
| GetType() |
Obtém o tipo de runtime da instância atual. (Herdado de Exception) |
| MemberwiseClone() |
Cria uma cópia superficial do Objectatual. (Herdado de Object) |
| ToString() |
Cria e retorna uma representação de cadeia de caracteres da exceção atual. (Herdado de Exception) |
Eventos
| Nome | Description |
|---|---|
| SerializeObjectState |
Obsoleto.
Ocorre quando uma exceção é serializada para criar um objeto de estado de exceção que contém dados serializados sobre a exceção. (Herdado de Exception) |