Desafio: 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
1234567891011121314151617try { // 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:
DivideByZeroException
: ocorre uma divisão por zero;FileNotFoundException
: o arquivo acessado não existe;KeyNotFoundException
: a chave do dicionário não existe;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
12345678910111213try { // code } catch (ExceptionType) { // code } ... finally { // code }
Aqui está um exemplo de uso desse tipo de bloco try-catch
:
index.cs
123456789101112131415161718192021222324252627using 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
1234567891011121314151617181920212223242526272829303132333435using 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
1234567891011121314151617181920212223242526272829303132333435using 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"); } } } }
Obrigado pelo seu feedback!
Pergunte à IA
Pergunte à IA
Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo
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
Desafio: 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
1234567891011121314151617try { // 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:
DivideByZeroException
: ocorre uma divisão por zero;FileNotFoundException
: o arquivo acessado não existe;KeyNotFoundException
: a chave do dicionário não existe;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
12345678910111213try { // code } catch (ExceptionType) { // code } ... finally { // code }
Aqui está um exemplo de uso desse tipo de bloco try-catch
:
index.cs
123456789101112131415161718192021222324252627using 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
1234567891011121314151617181920212223242526272829303132333435using 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
1234567891011121314151617181920212223242526272829303132333435using 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"); } } } }
Obrigado pelo seu feedback!