Menu
Coddy logo textTech

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 DivideByZeroException

Puedes 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);
}
challenge icon

Desafío

Fácil

Crea un método llamado ProcessArray que:

  1. Toma un arreglo de enteros y un índice como parámetros
  2. Intenta acceder al elemento en el índice especificado
  3. Devuelve el valor del elemento si es exitoso
  4. 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 NullReferenceException

IndexOutOfRangeException: Se lanza cuando el índice del array está fuera de los límites:

int[] numbers = { 1, 2, 3 };
int value = numbers[5]; // Throws IndexOutOfRangeException

DivideByZeroException: Se lanza al dividir un entero por cero:

int result = 10 / 0; // Throws DivideByZeroException

Capturando 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);
    }
}
quiz iconPonte a prueba

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