Home > OS >  Can't catch NullReferenceException while explicitly defined for that
Can't catch NullReferenceException while explicitly defined for that

Time:10-03

I'm using this code to run async function

private async Task SearchMostLessViewsAsync(DateTime dateFrom, DateTime dateTo, int amountOfNumbersSelected, int frequencyOption, int fromDrawNumber, int toDrawNumber)
    {
        Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{typeof(FragmentDrawsNumbersFrequency).Name}.{nameof(SearchMostLessViewsAsync)}",
            new Dictionary<string, string>()
                {
                    {nameof(dateFrom), dateFrom.ToString()},
                    {nameof(dateTo), dateTo.ToString()},
                    {nameof(amountOfNumbersSelected), amountOfNumbersSelected.ToString()},
                    {nameof(frequencyOption), frequencyOption.ToString()},
                    {nameof(fromDrawNumber), fromDrawNumber.ToString()},
                    {nameof(toDrawNumber), toDrawNumber.ToString()},
                }
            );
        ((MainActivity)Activity).DisplayLoadingMessage(true, GetString(Resource.String.Common_SearchTitle),
            GetString(Resource.String.Common_SearchMessage));

        //ApplicationState.ChangeCancellationTokenSource(new CancellationTokenSource());

        var task = Task.Run(async () =>
        {
            var textResult = await SearchLeast(dateFrom, dateTo, amountOfNumbersSelected, frequencyOption, fromDrawNumber, toDrawNumber).ConfigureAwait(false);

            if (!string.IsNullOrEmpty(textResult))
            {
                UpdateHistoryList(textResult);
                DatabaseFunctions.SaveHistoryList(HistoryList, Settings.DrawsNumbersFrequencyHistoryListViewKey);

                ((MainActivity)Activity).ShowSearchResults(textResult);
            }
        }, ApplicationState.GetCancellationToken()); // Pass same token to Task.Run.

        try
        {
            await task.ConfigureAwait(false);
        }
        catch (TaskCanceledException tce)
        {
            Console.WriteLine($"{nameof(TaskCanceledException)} thrown with message: {tce.Message}");
        }
        catch (System.ObjectDisposedException ode)
        {
            Console.WriteLine($"{nameof(System.ObjectDisposedException)} thrown with message: {ode.Message}");
        }
        catch (System.OperationCanceledException e)
        {
            Console.WriteLine($"{nameof(System.OperationCanceledException)} thrown with message: {e.Message}");
        }
        catch (NullReferenceException nre)
        {
            Console.WriteLine($"{nameof(NullReferenceException)} thrown with message: {nre.Message}");
        }
        finally
        {
            ApplicationState.DisposeCancellationTokenSource();
            ((MainActivity)Activity).DisplayLoadingMessage(false);
        }

        ((MainActivity)Activity).DisplayLoadingMessage(false);
    }

But sometimes i get this exception

FragmentDrawsNumbersFrequency.SearchMostLessViewsAsync (System.DateTime dateFrom, System.DateTime dateTo, System.Int32 amountOfNumbersSelected, System.Int32 frequencyOption, System.Int32 fromDrawNumber, System.Int32 toDrawNumber)
FragmentDrawsNumbersFrequency.ShowMostLessViews ()
FragmentDrawsNumbersFrequency.<OnCreateView>b__50_8 (System.Object sender, System.EventArgs e)
AsyncMethodBuilderCore <>c.<ThrowAsync>b__7_0 (System.Object state)
SyncContext <>c__DisplayClass2_0.<Post>b__0 ()
Thread RunnableImplementor.Run ()
IRunnableInvoker.n_Run (System.IntPtr jnienv, System.IntPtr native__this)
(wrapper dynamic-method) Android.Runtime.DynamicMethodNameCounter.61(intptr,intptr)

I'm not sure why. Shouldn't the try catch wrap catch nullreference exceptions?

CodePudding user response:

Currently you would catch NullReferenceException only if task is null, which obviously isn't the case.

You probably want to do try/catch inside the task.

  • Related