The following code does not catch my OperationCancelException which is thrown by calling ct.ThrowIfCancellationRequested
.
public partial class Title
In your first example the exception is not caught because it does not occure before leaving the try/catch
block. If you want to catch it there you need to wait/await
it there exactly like you do in the second example.
If you do not await the returned task the method continues execution and leaves the try/catch
block before the exception actually occures...
If you want to catch the exception "out of band" you can also register to TaskScheduler.UnobservedTaskException
(this event is called if a task is throwing an exception which is nowhere caught) to get all uncaught exceptions or monitor the tasks Exception property. May also check out THIS answer.
Exeption is thrown in the task on another thread.
public async Task GetCancelExceptionAsync(CancellationToken ct)
{
try
{
await Task.Delay(1000);
ct.ThrowIfCancellationRequested();
}
catch (Exception e)
{
// your Cancleation expeption
}
}