Exception Types
Parte de la sección Lógica y Flujo del Journey de C# de Coddy — lección 24 de 66.
En C#, las excepciones se clasifican en diferentes tipos según el error que representan. Comprender estos tipos te ayuda a manejar los errores de manera más efectiva.
Veamos los tipos de excepciones comunes:
La clase base para todas las excepciones es System.Exception.
try
{
// Código que podría lanzar una excepción
}
catch (Exception ex)
{
// Manejar cualquier excepción
Console.WriteLine(ex.Message);
}Algunos tipos de excepciones comunes:
ArgumentException: Se lanza cuando se llama a un método con un argumento inválido.
string name = null;
if (name == null)
{
throw new ArgumentException("Name cannot be null");
}NullReferenceException: Se lanza cuando intentas acceder a un miembro en una referencia nula.
string text = null;
// Esto lanzará NullReferenceException
int length = text.Length;IndexOutOfRangeException: Se lanza cuando un índice de array está fuera de los límites del array.
int[] numbers = { 1, 2, 3 };
// This will throw IndexOutOfRangeException
int value = numbers[5];DivideByZeroException: Se lanza cuando se divide un entero por cero.
int result = 10 / 0; // This will throw DivideByZeroExceptionPuedes capturar excepciones específicas:
try
{
int[] numbers = { 1, 2, 3 };
int value = numbers[5];
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine("Array index error: " + ex.Message);
}
catch (Exception ex)
{
Console.WriteLine("General error: " + ex.Message);
}Desafío
FácilCrea un método llamado ProcessArray que:
- Toma un arreglo de enteros y un índice como parámetros
- Intenta acceder al elemento en el índice especificado
- Devuelve el valor del elemento si es exitoso
- Si ocurre un
IndexOutOfRangeException, captúralo y devuelve -1
Tu método debe tener esta firma:
public static int ProcessArray(int[] array, int index)Hoja de referencia
La clase base para todas las excepciones es System.Exception:
try
{
// Code that might throw an exception
}
catch (Exception ex)
{
// Handle any exception
Console.WriteLine(ex.Message);
}Tipos comunes de excepciones:
ArgumentException: Se lanza cuando se llama a un método con un argumento inválido:
string name = null;
if (name == null)
{
throw new ArgumentException("Name cannot be null");
}NullReferenceException: Se lanza al acceder a un miembro en una referencia nula:
string text = null;
int length = text.Length; // Throws NullReferenceExceptionIndexOutOfRangeException: Se lanza cuando el índice del array está fuera de los límites:
int[] numbers = { 1, 2, 3 };
int value = numbers[5]; // Throws IndexOutOfRangeExceptionDivideByZeroException: Se lanza al dividir un entero por cero:
int result = 10 / 0; // Throws DivideByZeroExceptionCapturando excepciones específicas:
try
{
int[] numbers = { 1, 2, 3 };
int value = numbers[5];
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine("Array index error: " + ex.Message);
}
catch (Exception ex)
{
Console.WriteLine("General error: " + ex.Message);
}Pruébalo tú mismo
using System;
class Program
{
public static int ProcessArray(int[] array, int index)
{
// Escribe tu código aquí
return 0;
}
static void Main(string[] args)
{
// Leer entrada del array
string input = Console.ReadLine();
// Quitar corchetes si están presentes
if (input.StartsWith("[") && input.EndsWith("]"))
{
input = input.Substring(1, input.Length - 2);
}
string[] parts = input.Split(',');
int[] array = new int[parts.Length];
for (int i = 0; i < parts.Length; i++)
{
array[i] = int.Parse(parts[i].Trim());
}
// Leer entrada del índice
int index = int.Parse(Console.ReadLine());
int result = ProcessArray(array, index);
Console.WriteLine(result);
}
}Esta lección incluye un breve cuestionario. Empieza la lección para responderlo y registrar tu progreso.
Todas las lecciones de Lógica y Flujo
1Multi-dimensional Arrays
2D Arrays BasicsDeclaring and Initializing 2DAccessing 2D Array ElementsNested Loops with 2D ArraysJagged ArraysCommon Matrix OperationsRecap - Multi-dimensional4Flow Control Techniques
Early ReturnsGuard ClausesJump Statements (goto)Break and ContinueFlatten Nested Conditionals7Logical Operators Advanced
Short-Circuit EvaluationConditional Logical OperatorsOperator PrecedenceRecap - Advanced Operators2Advanced Decision Making
Multiple ConditionsComplex Boolean LogicIf vs. Switch ComparisonNested Switch StatementsRecap - Advanced Decisions5Exception Handling
Try-Catch BasicsException TypesMultiple Catch BlocksWorking with FilesFinally BlockUsing vs. Try-FinallyCustom ExceptionsRecap - Error Handling3Loop Enhancements
Loop PerformanceIterating ComplexEach Loop TypeRefactoring LoopsRecap - Optimized Loops6Null Handling
Null Reference BasicsNullable Value TypesNull Checking PatternsDefensive ProgrammingRecap - Null Safety