Menu
Coddy logo textTech

Exception Types

Parte da seção Lógica & Fluxo do Journey de C# da Coddy — lição 24 de 66.

No C#, as exceções são categorizadas em diferentes tipos com base no erro que representam. Compreender esses tipos ajuda você a lidar com erros de forma mais eficaz.

Vamos ver os tipos comuns de exceções:

A classe base para todas as exceções é System.Exception.

try
{
    // Código que pode lançar uma exceção
}
catch (Exception ex)
{
    // Trate qualquer exceção
    Console.WriteLine(ex.Message);
}

Alguns tipos comuns de exceções:

ArgumentException: Lançada quando um método é chamado com um argumento inválido.

string name = null;
if (name == null)
{
    throw new ArgumentException("Name cannot be null");
}

NullReferenceException: Lançada quando você tenta acessar um membro em uma referência nula.

string text = null;
// Isso lançará NullReferenceException
int length = text.Length;

IndexOutOfRangeException: Lançada quando um índice de array está fora dos limites do array.

int[] numbers = { 1, 2, 3 };
// Isso lançará IndexOutOfRangeException
int value = numbers[5];

DivideByZeroException: Lançada quando um inteiro é dividido por zero.

int result = 10 / 0; // This will throw DivideByZeroException

Você pode capturar exceções 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

Desafio

Fácil

Crie um método chamado ProcessArray que:

  1. Recebe um array de inteiros e um índice como parâmetros
  2. Tenta acessar o elemento no índice especificado
  3. Retorna o valor do elemento se bem-sucedido
  4. Se uma IndexOutOfRangeException ocorrer, capture-a e retorne -1

Seu método deve ter esta assinatura:

public static int ProcessArray(int[] array, int index)

Folha de consulta

A classe base para todas as exceções é System.Exception:

try
{
    // Code that might throw an exception
}
catch (Exception ex)
{
    // Handle any exception
    Console.WriteLine(ex.Message);
}

Tipos comuns de exceções:

ArgumentException: Lançada quando um método é chamado com um argumento inválido:

string name = null;
if (name == null)
{
    throw new ArgumentException("Name cannot be null");
}

NullReferenceException: Lançada ao acessar um membro em uma referência nula:

string text = null;
int length = text.Length; // Throws NullReferenceException

IndexOutOfRangeException: Lançada quando o índice do array está fora dos limites:

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

DivideByZeroException: Lançada ao dividir um inteiro por zero:

int result = 10 / 0; // Throws DivideByZeroException

Capturando exceções 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);
}

Experimente você mesmo

using System;

class Program
{
    public static int ProcessArray(int[] array, int index)
    {
        // Escreva seu código aqui
        return 0;
    }

    static void Main(string[] args)
    {
        // Ler entrada do array
        string input = Console.ReadLine();
        
        // Remover colchetes se 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());
        }
        
        // Ler entrada do índice
        int index = int.Parse(Console.ReadLine());
        
        int result = ProcessArray(array, index);
        Console.WriteLine(result);
    }
}
quiz iconTeste seus conhecimentos

Esta lição inclui um quiz rápido. Comece a lição para respondê-lo e acompanhar seu progresso.

Todas as lições de Lógica & Fluxo