Course Content
C# Beyond Basics
C# Beyond Basics
Practicing Error Handling
The try-catch
syntax has an additional syntax which allows us to catch specific types of errors and deal with them separately:
index
try { // code } catch (ExceptionType errorVarName) { // code } catch (ExceptionType errorVarName) { // code } ... finally { // code }
The type Exception
we used in the previous chapter simply catches all kinds of errors however there are some subtypes of Exception
which catch more specific kinds of errors. Following are some common exception types:
DivideByZeroException
: There's a division by zero;FileNotFoundException
: The file we're accessing doesn't exist;KeyNotFoundException
: The dictionary key doesn't exist;IndexOutOfRangeException
: The specified index of an array or list is invalid.
The term errorVarName
is a variable which stores the Exception object, and has information like the error message which can be accessed through errorVarName.Message
. We can omit that in case we're not using it:
index
try { // code } catch (ExceptionType) { // code } ... finally { // code }
Here's an example of using this kind of try-catch block:
index
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; } } } }
Now using these concepts. Fill in the blanks with relevant exception types in the following code to complete the challenge.
index
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"); } } } }
Thanks for your feedback!