NullReferenceException Clase
Definición
Excepción que se produce cuando se intenta desreferenciar un objeto null.The exception that is thrown when there is an attempt to dereference a null object reference.
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
- Herencia
- Herencia
- Atributos
Comentarios
NullReferenceExceptionSe produce una excepción cuando se intenta obtener acceso a un miembro en un tipo cuyo valor es null
.A NullReferenceException exception is thrown when you try to access a member on a type whose value is null
. NullReferenceExceptionNormalmente, una excepción refleja el error del desarrollador y se produce en los siguientes escenarios:A NullReferenceException exception typically reflects developer error and is thrown in the following scenarios:
Ha olvidado crear una instancia de un tipo de referencia.You've forgotten to instantiate a reference type. En el ejemplo siguiente,
names
se declara pero nunca se crea una instancia de:In the following example,names
is declared but never instantiated: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()
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()
Algunos compiladores emiten una advertencia al compilar este código.Some compilers issue a warning when they compile this code. Otros emiten un error y se produce un error en la compilación.Others issue an error, and the compilation fails. Para solucionar este problema, cree una instancia del objeto de modo que su valor ya no sea
null
.To address this problem, instantiate the object so that its value is no longernull
. En el ejemplo siguiente se realiza una llamada al constructor de clase de un tipo.The following example does this by calling a type's class constructor.using System; using System.Collections.Generic; public class Example { public static void Main() { List<String> names = new List<String>(); 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
Ha olvidado acotar una matriz antes de inicializarla.You've forgotten to dimension an array before initializing it. En el ejemplo siguiente,
values
se declara como una matriz de enteros, pero el número de elementos que contiene nunca se especifica.In the following example,values
is declared to be an integer array, but the number of elements that it contains is never specified. Por lo tanto, el intento de inicializar sus valores produce una NullReferenceException excepción.The attempt to initialize its values therefore thrown a NullReferenceException exception.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()
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()
Puede eliminar la excepción declarando el número de elementos de la matriz antes de inicializarlo, como hace el ejemplo siguiente.You can eliminate the exception by declaring the number of elements in the array before initializing it, as the following example does.
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
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
Para obtener más información sobre cómo declarar e inicializar matrices, vea matrices y matrices.For more information on declaring and initializing arrays, see Arrays and Arrays.
Obtiene un valor devuelto null de un método y, a continuación, llama a un método en el tipo devuelto.You get a null return value from a method, and then call a method on the returned type. A veces, esto es el resultado de un error de documentación; la documentación no tiene en cuenta que una llamada al método puede devolver
null
.This sometimes is the result of a documentation error; the documentation fails to note that a method call can returnnull
. En otros casos, el código supone erróneamente que el método siempre devolverá un valor distinto de null .In other cases, your code erroneously assumes that the method will always return a non-null value.En el código del ejemplo siguiente se da por supuesto que el Array.Find método siempre devuelve
Person
un objeto cuyoFirstName
campo coincide con una cadena de búsqueda.The code in the following example assumes that the Array.Find method always returnsPerson
object whoseFirstName
field matches a search string. Dado que no hay ninguna coincidencia, el tiempo de ejecución produce una NullReferenceException excepción.Because there is no match, the runtime throws a NullReferenceException exception.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()
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 solucionar este problema, pruebe el valor devuelto del método para asegurarse de que no es
null
antes de llamar a cualquiera de sus miembros, como se hace en el ejemplo siguiente.To address this problem, test the method's return value to ensure that it is notnull
before calling any of its members, as the following example does.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
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
Está utilizando una expresión (por ejemplo, está encadenando una lista de métodos o propiedades conjuntamente) para recuperar un valor y, aunque está comprobando si el valor es
null
, el tiempo de ejecución todavía produce una NullReferenceException excepción.You're using an expression (for example, you're chaining a list of methods or properties together) to retrieve a value and, although you're checking whether the value isnull
, the runtime still throws a NullReferenceException exception. Esto se debe a que uno de los valores intermedios de la expresión devuelvenull
.This occurs because one of the intermediate values in the expression returnsnull
. Como resultado, la prueba denull
nunca se evalúa.As a result, your test fornull
is never evaluated.En el ejemplo siguiente se define un
Pages
objeto que almacena en memoria caché la información sobre las páginas web, que se presentan porPage
objetos.The following example defines aPages
object that caches information about web pages, which are presented byPage
objects. ElExample.Main
método comprueba si la página web actual tiene un título no nulo y, si lo hace, muestra el título.TheExample.Main
method checks whether the current web page has a non-null title and, if it does, displays the title. Sin embargo, a pesar de esta comprobación, el método produce una NullReferenceException excepción.Despite this check, however, the method throws a NullReferenceException exception.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()
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()
La excepción se produce porque
pages.CurrentPage
devuelvenull
si no hay información de página almacenada en la memoria caché.The exception is thrown becausepages.CurrentPage
returnsnull
if no page information is stored in the cache. Esta excepción se puede corregir comprobando el valor de laCurrentPage
propiedad antes de recuperar laPage
propiedad del objeto actualTitle
, como hace el ejemplo siguiente:This exception can be corrected by testing the value of theCurrentPage
property before retrieving the currentPage
object'sTitle
property, as the following example does: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.
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.
Está enumerando los elementos de una matriz que contiene tipos de referencia y el intento de procesar uno de los elementos produce una NullReferenceException excepción.You're enumerating the elements of an array that contains reference types, and your attempt to process one of the elements throws a NullReferenceException exception.
En el ejemplo siguiente se define una matriz de cadenas.The following example defines a string array. Una
for
instrucción enumera los elementos de la matriz y llama al método de cada cadena Trim antes de mostrar la cadena.Afor
statement enumerates the elements in the array and calls each string's Trim method before displaying the string.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()
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()
Esta excepción se produce si se asume que cada elemento de la matriz debe contener un valor distinto de NULL y el valor del elemento de matriz es de hecho
null
.This exception occurs if you assume that each element of the array must contain a non-null value, and the value of the array element is in factnull
. La excepción se puede eliminar comprobando si el elemento esnull
antes de realizar cualquier operación en dicho elemento, como se muestra en el ejemplo siguiente.The exception can be eliminated by testing whether the element isnull
before performing any operation on that element, as the following example shows.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
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
Un NullReferenceException método que se pasa produce una excepción
null
.A NullReferenceException exception is thrown by a method that is passednull
. Algunos métodos validan los argumentos que se les pasan.Some methods validate the arguments that are passed to them. Si lo hacen y uno de los argumentos esnull
, el método produce una System.ArgumentNullException excepción.If they do and one of the arguments isnull
, the method throws an System.ArgumentNullException exception. De lo contrario, produce una NullReferenceException excepción.Otherwise, it throws a NullReferenceException exception. Este escenario se ilustra en el ejemplo siguiente.The following example illustrates this scenario.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()
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 solucionar este problema, asegúrese de que el argumento pasado al método no es
null
o controle la excepción iniciada en untry…catch…finally
bloque.To address this issue, make sure that the argument passed to the method is notnull
, or handle the thrown exception in atry…catch…finally
block. Para obtener más información, consulta Excepciones.For more information, see Exceptions.
Las siguientes instrucciones del lenguaje intermedio de Microsoft (MSIL) producen NullReferenceException : callvirt
, cpblk
, cpobj
, initblk
, ldelem.<type>
, ldelema
, ldfld
, ldflda
, ldind.<type>
, ldlen
, stelem.<type>
, stfld
,, stind.<type>
throw
y unbox
.The following Microsoft intermediate language (MSIL) instructions throw NullReferenceException: callvirt
, cpblk
, cpobj
, initblk
, ldelem.<type>
, ldelema
, ldfld
, ldflda
, ldind.<type>
, ldlen
, stelem.<type>
, stfld
, stind.<type>
, throw
, and unbox
.
NullReferenceException utiliza el COR_E_NULLREFERENCE HRESULT, que tiene el valor 0x80004003.NullReferenceException uses the HRESULT COR_E_NULLREFERENCE, which has the value 0x80004003.
Para obtener una lista de valores de propiedad iniciales de una instancia de NullReferenceException, consulte el NullReferenceException constructores.For a list of initial property values for an instance of NullReferenceException, see the NullReferenceException constructors.
Controlar NullReferenceException en el código de la versiónHandling NullReferenceException in release code
Normalmente es mejor evitar una excepción NullReferenceException que controlarla una vez que se produce.It's usually better to avoid a NullReferenceException than to handle it after it occurs. Controlar una excepción puede dificultar el mantenimiento y la comprensión del código y, a veces, puede introducir otros errores.Handling an exception can make your code harder to maintain and understand, and can sometimes introduce other bugs. Las excepciones NullReferenceException suelen ser errores sin recuperación.A NullReferenceException is often a non-recoverable error. En esos casos, la mejor opción puede ser permitir que la excepción detenga la aplicación.In these cases, letting the exception stop the app might be the best alternative.
Sin embargo, hay muchas situaciones en las que puede ser útil controlar el error:However, there are many situations where handling the error can be useful:
La aplicación puede pasar por alto los objetos que son NULL.Your app can ignore objects that are null. Por ejemplo, si la aplicación recupera y procesa los registros de una base de datos, puede caber la opción de pasar por alto cierto número de registros incorrectos que generan objetos NULL.For example, if your app retrieves and processes records in a database, you might be able to ignore some number of bad records that result in null objects. Es posible que solo tenga que registrar los datos incorrectos en un archivo de registro o en la interfaz de usuario de la aplicación.Recording the bad data in a log file or in the application UI might be all you have to do.
La recuperación tras la excepción es posible.You can recover from the exception. Por ejemplo, una llamada a un servicio Web que devuelve un tipo de referencia podría devolver null si se pierde la conexión o se agota el tiempo de espera de la conexión. Puede intentar restablecer la conexión y volver a intentar la llamada.For example, a call to a web service that returns a reference type might return null if the connection is lost or the connection times out. You can attempt to reestablish the connection and try the call again.
Puede restaurar el estado de la aplicación a un estado válido.You can restore the state of your app to a valid state. Por ejemplo, puede que esté realizando una tarea con varios pasos que exija guardar información en un almacén de datos antes de llamar a un método que lance una excepción NullReferenceException.For example, you might be performing a multi-step task that requires you to save information to a data store before you call a method that throws a NullReferenceException. Si el objeto sin inicializar fuera a dañar el registro de datos, puede quitar los datos anteriores antes de cerrar la aplicación.If the uninitialized object would corrupt the data record, you can remove the previous data before you close the app.
La excepción se tiene que notificar.You want to report the exception. Por ejemplo, si la causa del error fue un error del usuario de la aplicación, puede generar un mensaje para indicarle cómo proporcionar la información correcta.For example, if the error was caused by a mistake from the user of your app, you can generate a message to help him supply the correct information. También puede registrar información sobre el error para facilitar la resolución del problema.You can also log information about the error to help you fix the problem. Algunos marcos, como ASP.NET, tienen un controlador de excepciones de nivel superior que captura todos los errores para que la aplicación no se bloquee nunca. En ese caso, puede que la única forma de saber que se produce sea registrar la excepción.Some frameworks, like ASP.NET, have a high-level exception handler that captures all errors to that the app never crashes; in that case, logging the exception might be the only way you can know that it occurs.
Constructores
NullReferenceException() |
Inicializa una nueva instancia de la clase NullReferenceException, estableciendo la propiedad Message de una nueva instancia en un mensaje proporcionado por el sistema que describe el error, como "Se ha encontrado el valor 'null' en el lugar donde era necesaria una instancia de un objeto".Initializes a new instance of the NullReferenceException class, setting the Message property of the new instance to a system-supplied message that describes the error, such as "The value 'null' was found where an instance of an object was required." Este mensaje tiene en cuenta la referencia cultural del sistema actual.This message takes into account the current system culture. |
NullReferenceException(SerializationInfo, StreamingContext) |
Inicializa una nueva instancia de la clase NullReferenceException con datos serializados.Initializes a new instance of the NullReferenceException class with serialized data. |
NullReferenceException(String) |
Inicializa una nueva instancia de la clase NullReferenceException con el mensaje de error especificado.Initializes a new instance of the NullReferenceException class with a specified error message. |
NullReferenceException(String, Exception) |
Inicializa una nueva instancia de la clase NullReferenceException con el mensaje de error especificado y una referencia a la excepción interna que representa la causa de esta excepción.Initializes a new instance of the NullReferenceException class with a specified error message and a reference to the inner exception that is the cause of this exception. |
Propiedades
Data |
Obtiene una colección de pares clave/valor que proporciona información definida por el usuario adicional sobre la excepción.Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Heredado de Exception) |
HelpLink |
Obtiene o establece un vínculo al archivo de ayuda asociado a esta excepción.Gets or sets a link to the help file associated with this exception. (Heredado de Exception) |
HResult |
Obtiene o establece HRESULT, un valor numérico codificado que se asigna a una excepción específica.Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Heredado de Exception) |
InnerException |
Obtiene la instancia Exception que produjo la excepción actual.Gets the Exception instance that caused the current exception. (Heredado de Exception) |
Message |
Obtiene un mensaje que describe la excepción actual.Gets a message that describes the current exception. (Heredado de Exception) |
Source |
Devuelve o establece el nombre de la aplicación o del objeto que generó el error.Gets or sets the name of the application or the object that causes the error. (Heredado de Exception) |
StackTrace |
Obtiene una representación de cadena de los marcos inmediatos en la pila de llamadas.Gets a string representation of the immediate frames on the call stack. (Heredado de Exception) |
TargetSite |
Obtiene el método que produjo la excepción actual.Gets the method that throws the current exception. (Heredado de Exception) |
Métodos
Equals(Object) |
Determina si el objeto especificado es igual que el objeto actual.Determines whether the specified object is equal to the current object. (Heredado de Object) |
GetBaseException() |
Cuando se invalida en una clase derivada, devuelve la clase Exception que representa la causa principal de una o más excepciones posteriores.When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Heredado de Exception) |
GetHashCode() |
Sirve como la función hash predeterminada.Serves as the default hash function. (Heredado de Object) |
GetObjectData(SerializationInfo, StreamingContext) |
Cuando se invalida en una clase derivada, establece SerializationInfo con información sobre la excepción.When overridden in a derived class, sets the SerializationInfo with information about the exception. (Heredado de Exception) |
GetType() |
Obtiene el tipo de tiempo de ejecución de la instancia actual.Gets the runtime type of the current instance. (Heredado de Exception) |
MemberwiseClone() |
Crea una copia superficial del Object actual.Creates a shallow copy of the current Object. (Heredado de Object) |
ToString() |
Crea y devuelve una representación de cadena de la excepción actual.Creates and returns a string representation of the current exception. (Heredado de Exception) |
Eventos
SerializeObjectState |
Ocurre cuando una excepción se serializa para crear un objeto de estado de excepción que contenga datos serializados sobre la excepción.Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Heredado de Exception) |