-4

I don't understand the sense of error handling with try and catch. (C#) In my online course the following example was used:

class Program
{
    static void Main(string[] args)
    {

        try
        {
            int[] numbers = new int[3];

            numbers[1] = 0;
            numbers[2] = 1;
            numbers[3] = 2;
            numbers[4] = 3;
        }
        catch(IndexOutOfRangeException ex)
        {
            Console.WriteLine(ex.Message);
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.Message);
        }


        Console.ReadKey();
    }
}

This is a very simple example, but why would I do that?

Im a newbie... im learning to code C# ... But I try to learn it this way that in the best case no mistakes occur at all.

Why would I try to catch an exception like that instead of

run the programm -> "Ah there is a exeption" -> and then fix it?
Sinatr
  • 20,892
  • 15
  • 90
  • 319
Krunki
  • 5
  • 2
  • https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/try-catch – gunr2171 Mar 03 '21 at 13:48
  • 4
    well, if your program is running in _production_, you can not _fix it_. since it's running. so instead you tell your program how to handle the exception - for example by telling the user their input was invalid, or restarting a connection - instead of just... you know - _crashing_. or maybe you want to automatically log exceptions, so _you_ can see what has happened, but the user isn't confused by technical error messages they don't understand. – Franz Gleichmann Mar 03 '21 at 13:48
  • You write to catch errors so when they happen you dont break parts of your code after this. You write 2 catch like in your example if you want to capture 1 error and do something other than fail (maybe just capture it but continue) but you still want to capture the error. The 2nd one would probably cause a failure. You write them to catch unexpected things, if you knew about every possible outcome/input then you wouldnt need it, but that is not possible to know that. – Brad Mar 03 '21 at 13:49
  • 1
    Exception are by their nature _exceptional_ You have the correct mindset, work to avoid all imaginable exceptions, but (I would add) prepare yourself for the unforeseeable event and try to avoid a crash, if possible. – Steve Mar 03 '21 at 13:52
  • 1
    Not every exception is a bug, it could be a missing network connection or million other reasons. Normally you dont want that your program crashes then. Instead you want to log this error and inform the user in understandable words what happened and what he can do now. Maybe you also want to implement a [retry-pattern](https://learn.microsoft.com/en-us/azure/architecture/patterns/retry). – Tim Schmelter Mar 03 '21 at 13:53
  • Thanks a lot for the answers guys! It helps me a lot ! :) – Krunki Mar 03 '21 at 14:00

1 Answers1

0

First a small point, in C# array are 0 index based meaning you should begin with numbers[0].

In your case numbers[4] will fail but without try/catch the code would just stop instantly.

Most of the time you want to log what happened wrongly in your application so that's a first possible (and widely used) purpose of the try/catch mechanism.

Sometimes an operation is maybe not important enough to stop the program. Let's say you want to send statistic. If statistics failed to be send (network issue ?) you do not want your program to stop completly.

Another use case that required more fine grained catch is for example a retry mechanism. If something is crashing because of a network issue you can just retry it a few second later but if something is crashing because of an IndexOutOfRangeException it's an issue that will happen again and again so no need to even retry it (but you will probably log it).

Arcord
  • 1,724
  • 1
  • 11
  • 16