Desafío: Manejo de Errores
La sintaxis try-catch
tiene una sintaxis adicional que permite capturar tipos específicos de errores y tratarlos por separado:
index.cs
1234567891011121314151617try { // code } catch (ExceptionType errorVarName) { // code } catch (ExceptionType errorVarName) { // code } ... finally { // code }
El tipo Exception
utilizado en el capítulo anterior simplemente captura todo tipo de errores; sin embargo, existen algunos subtipos de Exception
que capturan errores más específicos. A continuación se presentan algunos tipos comunes de excepciones:
DivideByZeroException
: hay una división por cero;FileNotFoundException
: el archivo al que se intenta acceder no existe;KeyNotFoundException
: la clave del diccionario no existe;IndexOutOfRangeException
: el índice especificado de un arreglo o lista no es válido.
El término errorVarName
es una variable que almacena el objeto Exception y contiene información como el mensaje de error, al cual se puede acceder mediante errorVarName.Message
. Se puede omitir si no se va a utilizar:
index.cs
12345678910111213try { // code } catch (ExceptionType) { // code } ... finally { // code }
Aquí tienes un ejemplo de cómo utilizar este tipo de bloque 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; } } } }
Ahora, utilizando estos conceptos, completa los espacios en blanco con los tipos de excepciones relevantes en el siguiente código para finalizar el desafío.
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"); } } } }
Utiliza el tipo de excepción relevante para cada bloque catch
. Lee el código y comprende qué bloque catch
es el más adecuado para manejar un determinado tipo de excepción.
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"); } } } }
¡Gracias por tus comentarios!
Pregunte a AI
Pregunte a AI
Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla
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
Desafío: Manejo de Errores
Desliza para mostrar el menú
La sintaxis try-catch
tiene una sintaxis adicional que permite capturar tipos específicos de errores y tratarlos por separado:
index.cs
1234567891011121314151617try { // code } catch (ExceptionType errorVarName) { // code } catch (ExceptionType errorVarName) { // code } ... finally { // code }
El tipo Exception
utilizado en el capítulo anterior simplemente captura todo tipo de errores; sin embargo, existen algunos subtipos de Exception
que capturan errores más específicos. A continuación se presentan algunos tipos comunes de excepciones:
DivideByZeroException
: hay una división por cero;FileNotFoundException
: el archivo al que se intenta acceder no existe;KeyNotFoundException
: la clave del diccionario no existe;IndexOutOfRangeException
: el índice especificado de un arreglo o lista no es válido.
El término errorVarName
es una variable que almacena el objeto Exception y contiene información como el mensaje de error, al cual se puede acceder mediante errorVarName.Message
. Se puede omitir si no se va a utilizar:
index.cs
12345678910111213try { // code } catch (ExceptionType) { // code } ... finally { // code }
Aquí tienes un ejemplo de cómo utilizar este tipo de bloque 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; } } } }
Ahora, utilizando estos conceptos, completa los espacios en blanco con los tipos de excepciones relevantes en el siguiente código para finalizar el desafío.
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"); } } } }
Utiliza el tipo de excepción relevante para cada bloque catch
. Lee el código y comprende qué bloque catch
es el más adecuado para manejar un determinado tipo de excepción.
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"); } } } }
¡Gracias por tus comentarios!