ExcepcionesExceptions

Las excepciones en C# proporcionan una forma estructurada, uniforme y con seguridad de tipos de controlar las condiciones de error del nivel de sistema y de la aplicación.Exceptions in C# provide a structured, uniform, and type-safe way of handling both system level and application level error conditions. El mecanismo de excepción en C# es muy similar al de C++, con algunas diferencias importantes:The exception mechanism in C# is quite similar to that of C++, with a few important differences:

  • En C#, todas las excepciones deben estar representadas por una instancia de un tipo de clase derivado de System.Exception .In C#, all exceptions must be represented by an instance of a class type derived from System.Exception. En C++, cualquier valor de cualquier tipo se puede utilizar para representar una excepción.In C++, any value of any type can be used to represent an exception.
  • En C#, se puede usar un bloque finally (la instrucción try) para escribir el código de finalización que se ejecuta en la ejecución normal y en condiciones excepcionales.In C#, a finally block (The try statement) can be used to write termination code that executes in both normal execution and exceptional conditions. Este código es difícil de escribir en C++ sin duplicar el código.Such code is difficult to write in C++ without duplicating code.
  • En C#, las excepciones de nivel de sistema, como Overflow, división por cero y desreferencia nula, tienen clases de excepción bien definidas y se encuentran en un par de condiciones de error de nivel de aplicación.In C#, system-level exceptions such as overflow, divide-by-zero, and null dereferences have well defined exception classes and are on a par with application-level error conditions.

Causas de las excepcionesCauses of exceptions

Se puede producir una excepción de dos maneras diferentes.Exception can be thrown in two different ways.

  • Una throw instrucción (la instrucción throw) produce una excepción de inmediato y de forma incondicional.A throw statement (The throw statement) throws an exception immediately and unconditionally. El control nunca alcanza la instrucción inmediatamente después de throw .Control never reaches the statement immediately following the throw.
  • Ciertas condiciones excepcionales que surgen durante el procesamiento de instrucciones y expresiones de C# causan una excepción en determinadas circunstancias en las que la operación no se puede completar con normalidad.Certain exceptional conditions that arise during the processing of C# statements and expression cause an exception in certain circumstances when the operation cannot be completed normally. Por ejemplo, una operación de división de enteros (operador de división) produce una excepción System.DivideByZeroException si el denominador es cero.For example, an integer division operation (Division operator) throws a System.DivideByZeroException if the denominator is zero. Vea clases de excepción comunes para obtener una lista de las distintas excepciones que pueden producirse de esta manera.See Common Exception Classes for a list of the various exceptions that can occur in this way.

La clase System.ExceptionThe System.Exception class

La System.Exception clase es el tipo base de todas las excepciones.The System.Exception class is the base type of all exceptions. Esta clase tiene algunas propiedades importantes que comparten todas las excepciones:This class has a few notable properties that all exceptions share:

  • Message es una propiedad de solo lectura de tipo string que contiene una descripción inteligible de la razón de la excepción.Message is a read-only property of type string that contains a human-readable description of the reason for the exception.
  • InnerException es una propiedad de solo lectura de tipo Exception .InnerException is a read-only property of type Exception. Si su valor no es null, hace referencia a la excepción que provocó la excepción actual, es decir, la excepción actual se produjo en un bloque catch que controla el InnerException .If its value is non-null, it refers to the exception that caused the current exception—that is, the current exception was raised in a catch block handling the InnerException. De lo contrario, su valor es null, lo que indica que esta excepción no se produjo por otra excepción.Otherwise, its value is null, indicating that this exception was not caused by another exception. El número de objetos de excepción encadenados de esta manera puede ser arbitrario.The number of exception objects chained together in this manner can be arbitrary.

El valor de estas propiedades se puede especificar en llamadas al constructor de instancia para System.Exception .The value of these properties can be specified in calls to the instance constructor for System.Exception.

Cómo se controlan las excepcionesHow exceptions are handled

Las excepciones se controlan mediante una try instrucción (la instrucción try).Exceptions are handled by a try statement (The try statement).

Cuando se produce una excepción, el sistema busca la cláusula más cercana catch que pueda controlar la excepción, según lo determinado por el tipo en tiempo de ejecución de la excepción.When an exception occurs, the system searches for the nearest catch clause that can handle the exception, as determined by the run-time type of the exception. En primer lugar, se busca una instrucción de inclusión léxica en el método actual try y las cláusulas Catch asociadas de la instrucción try se consideran en orden.First, the current method is searched for a lexically enclosing try statement, and the associated catch clauses of the try statement are considered in order. Si se produce un error, se busca en el método que llamó al método actual una instrucción de inclusión léxica try que incluye el punto de la llamada al método actual.If that fails, the method that called the current method is searched for a lexically enclosing try statement that encloses the point of the call to the current method. Esta búsqueda continúa hasta que catch se encuentra una cláusula que puede controlar la excepción actual, mediante el nombre de una clase de excepción que es de la misma clase o una clase base, del tipo en tiempo de ejecución de la excepción que se está iniciando.This search continues until a catch clause is found that can handle the current exception, by naming an exception class that is of the same class, or a base class, of the run-time type of the exception being thrown. Una catch cláusula que no denomina una clase de excepción puede controlar cualquier excepción.A catch clause that doesn't name an exception class can handle any exception.

Una vez que se encuentra una cláusula catch coincidente, el sistema se prepara para transferir el control a la primera instrucción de la cláusula catch.Once a matching catch clause is found, the system prepares to transfer control to the first statement of the catch clause. Antes de que comience la ejecución de la cláusula catch, el sistema ejecuta en primer lugar, en orden, cualquier finally cláusula que se asociara con instrucciones try más anidada que la que capturó la excepción.Before execution of the catch clause begins, the system first executes, in order, any finally clauses that were associated with try statements more nested that than the one that caught the exception.

Si no se encuentra ninguna cláusula catch coincidente, se produce una de dos cosas:If no matching catch clause is found, one of two things occurs:

  • Si la búsqueda de una cláusula catch coincidente alcanza un constructor estático (constructores estáticos) o un inicializador de campo estático, System.TypeInitializationException se produce una excepción en el punto que desencadenó la invocación del constructor estático.If the search for a matching catch clause reaches a static constructor (Static constructors) or static field initializer, then a System.TypeInitializationException is thrown at the point that triggered the invocation of the static constructor. La excepción interna de System.TypeInitializationException contiene la excepción que se produjo originalmente.The inner exception of the System.TypeInitializationException contains the exception that was originally thrown.
  • Si la búsqueda de cláusulas Catch coincidentes alcanza el código que inició inicialmente el subproceso, se termina la ejecución del subproceso.If the search for matching catch clauses reaches the code that initially started the thread, then execution of the thread is terminated. El impacto de dicha terminación está definido por la implementación.The impact of such termination is implementation-defined.

Las excepciones que se producen durante la ejecución de los destructores merecen mención especial.Exceptions that occur during destructor execution are worth special mention. Si se produce una excepción durante la ejecución del destructor y esa excepción no se detecta, se finaliza la ejecución de ese destructor y se llama al destructor de la clase base (si existe).If an exception occurs during destructor execution, and that exception is not caught, then the execution of that destructor is terminated and the destructor of the base class (if any) is called. Si no hay ninguna clase base (como en el caso del object tipo) o si no hay ningún destructor de clase base, se descartará la excepción.If there is no base class (as in the case of the object type) or if there is no base class destructor, then the exception is discarded.

Clases de excepciones comunesCommon Exception Classes

Ciertas operaciones de C# producen las excepciones siguientes.The following exceptions are thrown by certain C# operations.

System.ArithmeticException Una clase base para las excepciones que se producen durante las operaciones aritméticas, como System.DivideByZeroException y System.OverflowException.A base class for exceptions that occur during arithmetic operations, such as System.DivideByZeroException and System.OverflowException.
System.ArrayTypeMismatchException Se produce cuando se produce un error en un almacén de una matriz porque el tipo real del elemento almacenado es incompatible con el tipo real de la matriz.Thrown when a store into an array fails because the actual type of the stored element is incompatible with the actual type of the array.
System.DivideByZeroException Se produce cuando se intenta dividir un valor entero por cero.Thrown when an attempt to divide an integral value by zero occurs.
System.IndexOutOfRangeException Se produce cuando se intenta indexar una matriz a través de un índice que es menor que cero o fuera de los límites de la matriz.Thrown when an attempt to index an array via an index that is less than zero or outside the bounds of the array.
System.InvalidCastException Se produce cuando se produce un error en el tiempo de ejecución de una conversión explícita de un tipo base o una interfaz a un tipo derivado.Thrown when an explicit conversion from a base type or interface to a derived type fails at run time.
System.NullReferenceException Se produce cuando null se utiliza una referencia de una manera que hace que se requiera el objeto al que se hace referencia.Thrown when a null reference is used in a way that causes the referenced object to be required.
System.OutOfMemoryException Se produce cuando se produce un error al intentar asignar memoria (Via new ).Thrown when an attempt to allocate memory (via new) fails.
System.OverflowException Se inicia cuando se desborda una operación aritmética en un contexto checked.Thrown when an arithmetic operation in a checked context overflows.
System.StackOverflowException Se produce cuando la pila de ejecución se agota debido a que hay demasiadas llamadas a métodos pendientes; normalmente indica una recursividad muy profunda o sin enlazar.Thrown when the execution stack is exhausted by having too many pending method calls; typically indicative of very deep or unbounded recursion.
System.TypeInitializationException Se produce cuando un constructor estático produce una excepción y no catch existe ninguna cláusula para detectarlo.Thrown when a static constructor throws an exception, and no catch clauses exists to catch it.