0

I am trying to create a little application and display images of cats from thecatapi.com. I call CATS() on a timer every 10 seconds. The code runs fine for 3-5 images then i get "System.ArgumentException: 'parameter is not valid.'" Ive tried to use try/catch but it still throws an exception. Pointers as to a solution are much appreciated.

string catURL;
string catJSON;

private async void CATS()
{
    var client = new HttpClient();

    HttpResponseMessage response = await client.GetAsync("https://api.thecatapi.com/v1/images/search?api_key=<apiKey>");

    HttpContent responseContent = response.Content;

    using(var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
    {
        catJSON = (await reader.ReadToEndAsync());
    }
    dynamic items = JsonConvert.DeserializeObject(catJSON);
    foreach(var item in items)
    {
        catURL = Convert.ToString(item.url);
    }
    try
    {
        if (pictureBox1.Image != null)
            pictureBox1.Image.Dispose();
        pictureBox1.Load(catURL);
    }
    catch {}
}
Rahul Bhobe
  • 4,165
  • 4
  • 17
  • 32
Toby Hogg
  • 61
  • 1
  • 3
  • 1
    `catch { }` is pretty useless. Add some code there to print out the error. – 001 Mar 02 '21 at 22:01
  • Sorry to sound stupid but how would i do that? – Toby Hogg Mar 02 '21 at 22:03
  • 1
    @TobyHogg easiest would be if you look up the microsoft docs for try-catch. – Vulpex Mar 02 '21 at 22:05
  • 1
    Something like: `catch (Exception e) { Console.WriteLine(e.StackTrace);}` See also: [Exceptions and Exception Handling (C# Programming Guide)](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/exceptions/) – 001 Mar 02 '21 at 22:05
  • 1
    Needn't be the problem, but it is recommended not to dispose of a pbox.Image directly. Instead do the little dance: `Image dummy = pictureBox1.Image; pictureBox1.Image = null; if (dummy != null) dummy.Dispose();` – TaW Mar 02 '21 at 22:05
  • Catch is not actually happening. The exception is thrown within the try so I get no output – Toby Hogg Mar 02 '21 at 22:13
  • That means the error is before the `try`. Put the entire function inside the `try`. – 001 Mar 02 '21 at 22:41
  • 1
    Did you try my advice? – TaW Mar 03 '21 at 08:31
  • The error is Inside the try, I can move the try to the entire function and it still throws an exception. It is weird that it bypasses the try/catch though. – Toby Hogg Mar 03 '21 at 12:45
  • @TaW your advice did work thank you. – Toby Hogg Mar 03 '21 at 12:46

0 Answers0