Loading...

C# Exceptions

Keep a small int array slots that holds 2 and 4. Write slots[0] so the screen shows 2. Then learn what happens if you ask for slots[5] instead: C# throws IndexOutOfRangeException and the program stops. Keep the work in Pine with Main. Run with dotnet run for the safe file first. Seeing a run-time stop from a broken rule — not a missing semicolon — is what this page teaches. Leave try and catch for the next page. Keep the starting public class named Pine.

A safe read that finishes

An exception is C#'s way of saying a rule broke while the program was running. Until now most demos printed a clear line and ended quietly. This page keeps one quiet demo first, then one demo that stops with an exception name. You do not catch the exception here. You learn to recognize the stop.
Open the Pine file. The starting class name stays Pine. This page does not rename the starter. Delete any leftover int? size demo that prints HasValue and Value. Delete any foreach bag leftover. Delete any ReadLine line. The file you keep has no wait for typing. A clean Main makes the safe one-line screen easy to trust.
At the top keep using System;. Inside Main, store two whole numbers:
int[] slots = {2, 4};
Then write:
Console.WriteLine(slots[0]);
Slot numbers start at zero. Slot zero holds 2. Save before you run. That quiet print is the first checkpoint. The bad-index file comes next so you can see the stop.

safe slots zero

csharp
using System;

public class Pine
{
    public static void Main()
    {
        int[] slots = {2, 4};
        Console.WriteLine(slots[0]);
    }
}

A bad index that throws

Change only the write line so it asks for a slot that was never written: slots[5]. The array still has only two slots. At run time C# throws an exception instead of printing a number.

bad index throws

csharp
using System;

public class Pine
{
    public static void Main()
    {
        int[] slots = {2, 4};
        Console.WriteLine(slots[5]);
    }
}

Run the bad-index file with dotnet run. This time the program does not print 2. The terminal shows an error report that names IndexOutOfRangeException. The run stops. Lines you might have imagined after that write do not run, because the exception already stopped the normal path. Notice that the project may still build — the bad index is a run-time problem, not a missing semicolon.
That stop is the lesson. You are not fixing the index on this page with try. You are learning to recognize that a broken rule at run time becomes an exception and ends the quiet path. Read the exception name in the report. Keep the bad-index file only to see that stop. Prefer the safe file when you want a quiet screen with 2. If you change the bad index back to slots[0], the quiet screen returns; that proves the stop came from the index, not from the class name Pine.
Do not treat the stack report as a normal WriteLine result. It is the runtime telling you what went wrong. Spelling of the exception type matters when you talk about it: IndexOutOfRangeException. Saying only "error" is too vague for this lesson — keep the full type name when you describe the stop.

Nullable leftover is not this crash

A third file reminds you of the previous page's int? demo. That demo prints True then 4 and finishes. It is not the exception story.

nullable leftover contrast

csharp
using System;

public class Pine
{
    public static void Main()
    {
        int? size = 4;
        Console.WriteLine(size.HasValue);
        Console.WriteLine(size.Value);
    }
}

Run the leftover contrast with dotnet run only if you need to see a quiet finish again. The screen shows True then 4. That proves a finished program is not the same as an exception stop. For the exceptions lesson, return to the safe slots[0] file when you want 2, and to the bad-index file when you want to see IndexOutOfRangeException.
Do not invent try or catch in the teaching files on this page. Those words belong to the next page. If you already know them, still leave them out here so the stop stays visible.

Compared with a build error

A missing semicolon fails at build time before the program runs. A bad array index can build cleanly and then throw at run time. This page focuses on the run-time stop. If dotnet run waits for typing, ReadLine is still in the file — delete it. If the screen shows True then 4, you are on the nullable leftover file. If the screen shows 2, you are on the safe slots file. If the terminal names IndexOutOfRangeException, you are on the bad-index file.
Writing slots[1] prints 4 and finishes — that is valid, but it is not the crash demo. Keep slots[5] when you want the exception stop. Writing slots[-1] can also throw; this page's kept crash demo uses slots[5] so the story matches the quiz.

What this leaves for try-catch

This page shows a quiet array read and a run that stops with IndexOutOfRangeException. A later page — try-catch — catches an exception so the program can continue with a message you write. Stay with recognizing the stop here. Do not invent catch blocks on this page; the lesson goal is the exception itself. When dotnet run prints 2 from the safe file, you have the quiet checkpoint. When the bad-index file names IndexOutOfRangeException, you have the stop checkpoint.
Do not nest a second Main. Do not leave nullable demos as the only teaching path for this page. Keep using System; for console writes. Keep the array length at two values so index 5 stays clearly out of range.

You can write int[] slots = {2, 4}; and Console.WriteLine(slots[0]);. Run with dotnet run. The screen shows 2. Asking for slots[5] instead throws IndexOutOfRangeException and stops the normal path. Think of an exception as a hard stop when a run-time rule breaks. Pine stays the door you open with dotnet run. The next page is try-catch, where you catch that kind of stop and print your own line.
Keep leftover int? demos out of the safe and bad-index files so the screen cannot show True then 4 by mistake when you meant 2 or an exception report. Those habits are the checkpoint before you move on. Build errors and run-time exceptions are different clocks — this page trains the run-time clock.

🧠 Test Your Knowledge

Ready to Start

Test Your Knowledge

Challenge yourself with this interactive quiz and see how well you understand the topic

❓
5
Questions
🎯
70%
To Pass
♾️
∞
Time
🔄
∞
Attempts

📝 Instructions

  • Read each question carefully
  • Select the best answer for each question
  • You can retake the quiz as many times as you want
  • Your progress will be shown at the top