2

How can I catch TimeoutException?

I want to catch TimeoutException after 3 secs. But after 3 secs it prints out TimeoutException whereas It's too long. Timeout! is expected.

With console application it doesn't catch TimeoutException.

public static void work()
{
    Thread.Sleep(3000);
    Console.WriteLine("TimeoutException");
    throw new TimeoutException();
}

public static void Main(string[] args)
{
    try
    {
        ThreadStart th = new ThreadStart(work);
        Thread t = new Thread(th);
        t.Start();
        //Execute SearchProgram
        t.Abort();
    }
    catch (ThreadInterruptedException)
    {
        Console.WriteLine("It's too long. Timeout!");
    }

    Console.WriteLine("Result : ~~~");
}
CSDev
  • 3,177
  • 6
  • 19
  • 37
OBO
  • 57
  • 1
  • 6
  • 1
    You're catching `ThreadInterruptedException` and not `TimeoutException` – MindSwipe Jul 29 '19 at 07:25
  • You threw `TimeoutException();` inside your `work` method and expecting to catch `ThreadInterruptedException`? – Sá´‡M Jul 29 '19 at 07:27
  • [Catching unhandled exception on separate thread](https://stackoverflow.com/questions/4284986/catching-unhandled-exception-on-separate-threads). – John Wu Jul 29 '19 at 07:28

2 Answers2

2

You are probably catching the wrong exception. According to the microsoft documentation (https://learn.microsoft.com/fr-fr/dotnet/api/system.timeoutexception?view=netframework-4.8) you should catch the TimeOutException class.

taktak
  • 90
  • 10
1

As others have been able to say you do not catch the good exception. But this is not the expected answer since the error of one thread can not be catched from another.

There are several ways to handle this case, which can be found in this answer.

An example for your case:

public static void work()
{
    Thread.Sleep(3000);
    Console.WriteLine("TimeoutException");
    throw new TimeoutException();
}

public static void Main(string[] args)
{
    Thread thread = new Thread(() => SafeExecute(() => work(), Handler));
    thread.Start();

    Console.WriteLine("Result : ~~~");
    Console.ReadLine();
}

private static void Handler(Exception exception)
{
    Console.WriteLine(exception);
}

private static void SafeExecute(Action test, Action<Exception> handler)
{
    try
    {
        test.Invoke();
    }
    catch (TimeoutException ex)
    {
        Console.WriteLine("It's too long. Timeout!");
    }
    catch (Exception ex)
    {
        Handler(ex);
    }
}
Guilhem Prev
  • 979
  • 5
  • 17