Loading...

C# try and catch

Wrap the bad slots[5] read in try and catch so the program does not end on IndexOutOfRangeException. Print blocked inside the catch, then print after outside both blocks. Keep the work in Pine with Main. Run with dotnet run. The screen should show blocked, then after. A second file keeps slots[0] inside try so the catch is skipped and the screen shows 2, then after. Leave throw for the next page. Keep the starting public class named Pine.

Catch the bad index

The exceptions page showed that printing slots[5] on {2, 4} throws IndexOutOfRangeException and stops the run. This page keeps the same array story and adds handling. Open the Pine file. The starting class name stays Pine. This page does not rename the starter. Delete leftover bare bad-index mains that stop without a catch. Delete leftover int? size demos that print HasValue and Value. Delete any ReadLine line. The program must not wait for typing. A clean Main makes the handled screen easy to trust.
At the top keep using System;. Inside Main, keep the same small array:
int[] slots = {2, 4};
Put the bad print inside try:
Console.WriteLine(slots[5]);
Then write a catch that names IndexOutOfRangeException and prints blocked. After the whole try and catch, print after. The catch parameter name can be a short letter such as e; you do not need to print the exception object on this page.

Pine catch bad index

csharp
using System;

public class Pine
{
    public static void Main()
    {
        int[] slots = {2, 4};
        try
        {
            Console.WriteLine(slots[5]);
        }
        catch (IndexOutOfRangeException e)
        {
            Console.WriteLine("blocked");
        }
        Console.WriteLine("after");
    }
}

Save, then run with dotnet run. The screen shows blocked, then after. The bad index still throws inside try. The catch handles that named exception and prints blocked. The line Console.WriteLine("after"); sits outside, so it still runs. The program does not end on that stop the way the bare exceptions bad-index file did.
Imagine a second print still inside try after slots[5], for example a line that would print rice. That line does not run. Catching the exception does not go back and finish the rest of try. Only the catch body runs for that stop, then control continues after the catch. Keep that idea clear: handling skips the leftover lines inside try after the throw point.
If the terminal waits for keyboard input, a ReadLine call from an older exercise is still in a file. Delete that call. If you see only a stack report and no blocked line, the catch is missing or the exception name does not match. If you see 2 alone with no after, you may still be running an old safe exceptions file — switch to the catch teaching file with dotnet run. If the screen shows True then 4, a nullable leftover is still the path you are running; replace it with the try and catch demo.
Notice that the project may still build before you run. The bad index inside try is a run-time stop that catch handles, not a missing semicolon. Spelling of the exception type in the catch clause matters: IndexOutOfRangeException. Saying only "error" is too vague for this lesson — keep the full type name when you describe the handled stop.

When try finishes, catch stays quiet

A second program uses the same try and catch shape, but the print inside try asks for a written slot: slots[0]. Every line inside try finishes. The catch body does not run.

Pine safe index skips catch

csharp
using System;

public class Pine
{
    public static void Main()
    {
        int[] slots = {2, 4};
        try
        {
            Console.WriteLine(slots[0]);
        }
        catch (IndexOutOfRangeException e)
        {
            Console.WriteLine("blocked");
        }
        Console.WriteLine("after");
    }
}

Run with dotnet run. The screen shows 2, then after. The word blocked is not printed, because there was no IndexOutOfRangeException. The catch stayed quiet. The after line still runs, because it sits outside both blocks — the same place it had in the catch demo.
Walk the contrast once. First file: bad index, catch prints blocked, then after. Second file: safe index, catch skipped, screen shows 2, then after. Both keep Pine and the same catch type name. Only the index inside try changes. That single change is enough to show when catch runs and when it does not.
Do not invent a throw statement on this page. You are catching an exception a bad array read already causes. The next page is about throwing on purpose. Also do not wrap every quiet print in the course inside try today — this lesson uses try where a known bad index needs a handled path. Keep using System; for console writes. Keep the array length at two values so index 5 stays clearly out of range when you want the catch path.

The catch name must match

The catch clause names one exception type. On this page that type is IndexOutOfRangeException, matching the bad index. If you wrote catch (NullReferenceException e) around slots[5] instead, that catch would not handle the stop. The program would still end with IndexOutOfRangeException, and neither blocked nor after would print for that mismatched catch. Keep the matching type in the teaching files.
Other exception names exist in C#. This page stays with one clear pair: a bad array index and IndexOutOfRangeException. You do not need a catalog of every catchable type before you practice this shape. Match the name you saw on the exceptions page. Do not nest a second Main. Do not leave bare stop demos as the only teaching path for this page.

Compared with the bare exceptions stop

On the exceptions page, dotnet run with slots[5] and no catch stopped and showed a stack report that named IndexOutOfRangeException. On this page, dotnet run with the same bad index inside try prints blocked and continues to after. The array story did not change. Handling did. Keep bare stop files only as history if they still sit nearby; run the catch teaching file for the demos so the screen matches this lesson.
Nullable history still prints True then 4 when you keep that older file. That path is not the catch story. Delete or ignore leftover int? demos inside Pine so the teaching file stays on int[] slots plus try and catch. If dotnet run waits for typing, ReadLine is still in the file — delete it. Writing slots[1] inside try would print 4 then after with catch quiet — valid, but it is not the catch demo. Keep slots[5] when you want blocked then after.

What this leaves for throwing

This page catches an exception a line already hits. The next page introduces throw so you can signal a problem yourself. Stay with matching catch and seeing after continue here. Do not add a manual throw as a requirement on these Pine files yet. When dotnet run prints blocked then after from the catch file, you have the handled checkpoint. When the safe try file prints 2 then after, you have the skip-catch checkpoint.

You can catch IndexOutOfRangeException from slots[5] and see blocked, then after. You can keep slots[0] inside try and see 2, then after, with catch skipped. Run each kept demo with dotnet run in turn. The catch name matched the bad-index stop. Think of try as the risky block and catch as the named handler that lets later lines run. Pine stays the door you open with dotnet run. The next page is throwing, where you cause a stop on purpose.
Keep the catch demo for a handled path. Keep the safe try for a quiet skip of catch. Keep manual throw off this page. Those three habits are the checkpoint before you move on. When blocked then after appear after the bad index run, try and catch did their job for this lesson and you are ready for the next topic about throwing.

🧠 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