Learn to Code via Tutorials on Repl.it!

← Back to all posts
Exceptions in C#
ANDREWVOSS (42)

Exceptions

If you've coded in any language, you've probably encountered an error message. You know how it goes, your compiler exits and you just have to read the message. Most of the time, you can just go in and fix the code, but in some situations that just isn't feasible. For example, with an exception. An exception is a type of error that happens when the program is run, rather than when it is compiled. User input is the main source of this. There are just too may possible inputs for you to debug them all. For example, let's say we have an arithmetic program that only works with int. If the user inputs a float into the program, it will crash with an error. we don't want that. There is, of course, a solution.

The solution

Before we get into the code, you should know that this tutorial is for C#. Although many of the concepts can be used in other languages, C# has especially great features for handling exceptions, as well as being easy to understand. Anyway, let's get started. To solve this problem, we'll be using the try statement. What this statement does is that it runs any code in the block, and catches potential exceptions. Example:

try {
 Console.WriteLine("Hello, world!");
}

This is functionally the same as just writing

Console.WriteLine("Hello, world!");

So why use try? As you may have guessed, it is because it catches exceptions. Just like if has the keyword else, try has catch. catch is the most important reason to use try. What catch does is that it checks for exceptions as the code runs. if there is an exception, instead of crashing the program, it will stop executing the code in the try statement. Here's an example:

try {
int[] Numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9};
Console.WriteLine(Numbers[10]); //Index out of range exception
}
catch (Exception e) {
Console.WriteLine(e.Message);
}

Since this code causes an exception, it will not run. In this case, the catch statement contains Exception e which means that it is passing the exception as an Exception object called e. Then it prints e.message, which is the exception message. So the basic syntax to use is:

try {
//code to be executed
}
catch (Exception e) {
Console.WriteLine(e.Message);
}

The attached repl below contains another example. Enter a number, and it picks that number from an array of 1 to 9, so if you enter 9 or more, it will return an error but not crash.

Thanks for reading!