Ask coding questions

← Back to all posts
Why won't it catch?
SamuelBlick (1)

Tried this but the program isn't catching the error to exit the loop and I'm not sure why. Double checked and I think it should work.

Answered by badst (655) [earned 5 cycles]
View Answer
Comments
hotnewtop
Coder100 (16869)

The error is on line 23 (I think). What happens is that screenWidth is still greater than max screenWidth, and so you are printing to something that isn't exist

badst (655)

@Coder100 Ye simple fix:

try {
  Console.SetCursorPosition(screenWidth, 0);
  Console.WriteLine(screenWidth);
}
catch(ArgumentOutOfRangeException ex) {}
SamuelBlick (1)

@Coder100 Ok, so I fixed that but the program is supposed to say the screen width and no matter the size I make it, it always says 79. Do you know why that is. When testing, it seemed fine until it hit the catch. Then it just set it to 79 (well it technically set it to 80 but I have screenWidth++ afterwards so it goes to 79). Also, how do I include code in my posts?

SamuelBlick (1)

@pepelaugh So it works in: Console.SetCursorPosition(screenWidth,0); but not in:
Console.WriteLine(screenWidth);

badst (655)

@SamuelBlick make it the same catch statement as above.. I gave you the code lol

SamuelBlick (1)

@pepelaugh Ok, now. it's saying 62 each time. Also, that's not the issue. If it was, the program would crash and not finish. It doesn't stop working, it just gives it some seemingly random number to use though after the break

Coder100 (16869)

why not try:

int screenWidth = 0;
    int screenHeight = 0;
    Console.Clear();
    while (true)
    {
      try
      {
        screenWidth++;
        Console.SetCursorPosition(screenWidth,0);
      }
      catch
      {
        break;
      }
    }

    Console.SetCursorPosition(screenWidth,0);
    Console.WriteLine(screenWidth);

@SamuelBlick

SamuelBlick (1)

@Coder100 Tried it (also you forgot the screenWidth--; so it doesn't crash) but it still didn't work, it did exactly the same thing by setting it ti 79 or 62 for seemingly no reason. Does it have to do with it not registering break properly?

SamuelBlick (1)

@pepelaugh Lol I just realized that the code actually worked. It was just the idea that repl.it always has a width of 80 and a height of 24, a fact that I did not know before lol.