Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprenda Desafio: Tratamento de Erros | Estruturas de Dados e Manipulação de Arquivos
C# Além do Básico

bookDesafio: Tratamento de Erros

A sintaxe try-catch possui uma sintaxe adicional que permite capturar tipos específicos de erros e tratá-los separadamente:

index.cs

index.cs

copy
1234567891011121314151617
try { // code } catch (ExceptionType errorVarName) { // code } catch (ExceptionType errorVarName) { // code } ... finally { // code }

O tipo Exception utilizado no capítulo anterior captura todos os tipos de erros, porém existem alguns subtipos de Exception que capturam erros mais específicos. A seguir estão alguns tipos comuns de exceções:

  1. DivideByZeroException: ocorre uma divisão por zero;
  2. FileNotFoundException: o arquivo acessado não existe;
  3. KeyNotFoundException: a chave do dicionário não existe;
  4. IndexOutOfRangeException: o índice especificado de um array ou lista é inválido.

O termo errorVarName é uma variável que armazena o objeto Exception e possui informações como a mensagem de erro, que pode ser acessada através de errorVarName.Message. É possível omitir esse termo caso não seja utilizado:

index.cs

index.cs

copy
12345678910111213
try { // code } catch (ExceptionType) { // code } ... finally { // code }

Aqui está um exemplo de uso desse tipo de bloco try-catch:

index.cs

index.cs

copy
123456789101112131415161718192021222324252627
using System; class Program { static void Main(string[] args) { int[] myArray = { 0, 2, 4, 6, 8, 10 }; int i = 0; while (true) { try { Console.Write(myArray[i] / i + " "); i++; } catch(DivideByZeroException) { i++; } catch(IndexOutOfRangeException) { break; } } } }

Agora, utilizando esses conceitos. Preencha as lacunas com os tipos de exceção relevantes no código a seguir para completar o desafio.

index.cs

index.cs

copy
1234567891011121314151617181920212223242526272829303132333435
using System; using System.Collections.Generic; class Program { static void Main(string[] args) { int[] numbers = { 1, 2, 5, 7, 9 }; var numberNames = new Dictionary<int, string>(); numberNames.Add(1, "One"); numberNames.Add(2, "Two"); numberNames.Add(5, "Five"); numberNames.Add(9, "Nine"); int i = 0; while (true) { try { int key = numbers[i]; Console.WriteLine($"{key} is {numberNames[key]}"); i++; } catch (___) { break; } catch (___) { numberNames.Add(7, "Seven"); } } } }

Utilize o tipo de exceção relevante para cada bloco catch. Leia o código e compreenda qual bloco catch é mais apropriado para tratar determinado tipo de exceção.

index.cs

index.cs

copy
1234567891011121314151617181920212223242526272829303132333435
using System; using System.Collections.Generic; public class HelloWorld { public static void Main(string[] args) { int[] numbers = { 1, 2, 5, 7, 9 }; var numberNames = new Dictionary<int, string>(); numberNames.Add(1, "One"); numberNames.Add(2, "Two"); numberNames.Add(5, "Five"); numberNames.Add(9, "Nine"); int i = 0; while (true) { try { int key = numbers[i]; Console.WriteLine($"{key} is {numberNames[key]}"); i++; } catch (IndexOutOfRangeException) { break; } catch (KeyNotFoundException) { numberNames.Add(7, "Seven"); } } } }
Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 1. Capítulo 10

Pergunte à IA

expand

Pergunte à IA

ChatGPT

Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo

Suggested prompts:

What are the correct exception types to fill in the blanks?

Can you explain why each exception type is used in this context?

Can you give more examples of specific exception types?

Awesome!

Completion rate improved to 2.04

bookDesafio: Tratamento de Erros

Deslize para mostrar o menu

A sintaxe try-catch possui uma sintaxe adicional que permite capturar tipos específicos de erros e tratá-los separadamente:

index.cs

index.cs

copy
1234567891011121314151617
try { // code } catch (ExceptionType errorVarName) { // code } catch (ExceptionType errorVarName) { // code } ... finally { // code }

O tipo Exception utilizado no capítulo anterior captura todos os tipos de erros, porém existem alguns subtipos de Exception que capturam erros mais específicos. A seguir estão alguns tipos comuns de exceções:

  1. DivideByZeroException: ocorre uma divisão por zero;
  2. FileNotFoundException: o arquivo acessado não existe;
  3. KeyNotFoundException: a chave do dicionário não existe;
  4. IndexOutOfRangeException: o índice especificado de um array ou lista é inválido.

O termo errorVarName é uma variável que armazena o objeto Exception e possui informações como a mensagem de erro, que pode ser acessada através de errorVarName.Message. É possível omitir esse termo caso não seja utilizado:

index.cs

index.cs

copy
12345678910111213
try { // code } catch (ExceptionType) { // code } ... finally { // code }

Aqui está um exemplo de uso desse tipo de bloco try-catch:

index.cs

index.cs

copy
123456789101112131415161718192021222324252627
using System; class Program { static void Main(string[] args) { int[] myArray = { 0, 2, 4, 6, 8, 10 }; int i = 0; while (true) { try { Console.Write(myArray[i] / i + " "); i++; } catch(DivideByZeroException) { i++; } catch(IndexOutOfRangeException) { break; } } } }

Agora, utilizando esses conceitos. Preencha as lacunas com os tipos de exceção relevantes no código a seguir para completar o desafio.

index.cs

index.cs

copy
1234567891011121314151617181920212223242526272829303132333435
using System; using System.Collections.Generic; class Program { static void Main(string[] args) { int[] numbers = { 1, 2, 5, 7, 9 }; var numberNames = new Dictionary<int, string>(); numberNames.Add(1, "One"); numberNames.Add(2, "Two"); numberNames.Add(5, "Five"); numberNames.Add(9, "Nine"); int i = 0; while (true) { try { int key = numbers[i]; Console.WriteLine($"{key} is {numberNames[key]}"); i++; } catch (___) { break; } catch (___) { numberNames.Add(7, "Seven"); } } } }

Utilize o tipo de exceção relevante para cada bloco catch. Leia o código e compreenda qual bloco catch é mais apropriado para tratar determinado tipo de exceção.

index.cs

index.cs

copy
1234567891011121314151617181920212223242526272829303132333435
using System; using System.Collections.Generic; public class HelloWorld { public static void Main(string[] args) { int[] numbers = { 1, 2, 5, 7, 9 }; var numberNames = new Dictionary<int, string>(); numberNames.Add(1, "One"); numberNames.Add(2, "Two"); numberNames.Add(5, "Five"); numberNames.Add(9, "Nine"); int i = 0; while (true) { try { int key = numbers[i]; Console.WriteLine($"{key} is {numberNames[key]}"); i++; } catch (IndexOutOfRangeException) { break; } catch (KeyNotFoundException) { numberNames.Add(7, "Seven"); } } } }
Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 1. Capítulo 10
some-alt