Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Can't catch NullReferenceException while explicitly defined for that

Can't catch NullReferenceException while explicitly defined for that

Scheduled Pinned Locked Moved C#
learning
12 Posts 3 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • E Offline
    E Offline
    Exoskeletor
    wrote on last edited by
    #1

    Hello fellow members. Im trying to understand why my code is not catching NullReferenceException and i cant figure it out. 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()
    {
    {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)
    
    P OriginalGriffO 3 Replies Last reply
    0
    • E Exoskeletor

      Hello fellow members. Im trying to understand why my code is not catching NullReferenceException and i cant figure it out. 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()
      {
      {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)
      
      P Offline
      P Offline
      Pete OHanlon
      wrote on last edited by
      #2

      The exception is referring to this method: SearchMostLessViewsAsync. That's not anywhere in the code you're showing here.

      Advanced TypeScript Programming Projects

      1 Reply Last reply
      0
      • E Exoskeletor

        Hello fellow members. Im trying to understand why my code is not catching NullReferenceException and i cant figure it out. 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()
        {
        {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)
        
        OriginalGriffO Offline
        OriginalGriffO Offline
        OriginalGriff
        wrote on last edited by
        #3

        As Pete has said, the error isn't in the code you show, nor is the method that throws the error directly called in any of that code. Run your program in the debugger and when it fails, it will show you the line it found the problem on. You can then start looking at the various parts of it to see what value is null and start looking back through your code to find out why. So put a breakpoint at the beginning of the method containing the error line, and run your program from the start again. This time, the debugger will stop before the error, and let you examine what is going on by stepping through the code looking at your values. But we can't do that - we don't have your code, we don't know how to use it if we did have it, we don't have your data. So try it - and see how much information you can find out!

        "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt AntiTwitter: @DalekDave is now a follower!

        "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
        "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

        P E 2 Replies Last reply
        0
        • OriginalGriffO OriginalGriff

          As Pete has said, the error isn't in the code you show, nor is the method that throws the error directly called in any of that code. Run your program in the debugger and when it fails, it will show you the line it found the problem on. You can then start looking at the various parts of it to see what value is null and start looking back through your code to find out why. So put a breakpoint at the beginning of the method containing the error line, and run your program from the start again. This time, the debugger will stop before the error, and let you examine what is going on by stepping through the code looking at your values. But we can't do that - we don't have your code, we don't know how to use it if we did have it, we don't have your data. So try it - and see how much information you can find out!

          "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt AntiTwitter: @DalekDave is now a follower!

          P Offline
          P Offline
          Pete OHanlon
          wrote on last edited by
          #4

          Richard? Are you saying I'm a complete and utter Richard? ;P

          Advanced TypeScript Programming Projects

          OriginalGriffO E 2 Replies Last reply
          0
          • P Pete OHanlon

            Richard? Are you saying I'm a complete and utter Richard? ;P

            Advanced TypeScript Programming Projects

            OriginalGriffO Offline
            OriginalGriffO Offline
            OriginalGriff
            wrote on last edited by
            #5

            No I'm saying I'm a complete and utter pillock ... :laugh: Sorry ... fixed. :-O

            "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt AntiTwitter: @DalekDave is now a follower!

            "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
            "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

            1 Reply Last reply
            0
            • OriginalGriffO OriginalGriff

              As Pete has said, the error isn't in the code you show, nor is the method that throws the error directly called in any of that code. Run your program in the debugger and when it fails, it will show you the line it found the problem on. You can then start looking at the various parts of it to see what value is null and start looking back through your code to find out why. So put a breakpoint at the beginning of the method containing the error line, and run your program from the start again. This time, the debugger will stop before the error, and let you examine what is going on by stepping through the code looking at your values. But we can't do that - we don't have your code, we don't know how to use it if we did have it, we don't have your data. So try it - and see how much information you can find out!

              "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt AntiTwitter: @DalekDave is now a follower!

              E Offline
              E Offline
              Exoskeletor
              wrote on last edited by
              #6

              oh yes you are right, sorry i have used the wrong part of the code. i edit the question again. I cant reproduce the bug in my device, it is happening in around 2% of the devices that is being used, this code is from an app that is available from google play already

              1 Reply Last reply
              0
              • P Pete OHanlon

                Richard? Are you saying I'm a complete and utter Richard? ;P

                Advanced TypeScript Programming Projects

                E Offline
                E Offline
                Exoskeletor
                wrote on last edited by
                #7

                what means to be a Richard? :) i didnt get the joke

                P OriginalGriffO 2 Replies Last reply
                0
                • E Exoskeletor

                  what means to be a Richard? :) i didnt get the joke

                  P Offline
                  P Offline
                  Pete OHanlon
                  wrote on last edited by
                  #8

                  Griff called me Richard. He's edited the post to use my name now.

                  Advanced TypeScript Programming Projects

                  1 Reply Last reply
                  0
                  • E Exoskeletor

                    what means to be a Richard? :) i didnt get the joke

                    OriginalGriffO Offline
                    OriginalGriffO Offline
                    OriginalGriff
                    wrote on last edited by
                    #9

                    I made a mistake, and referred to Pete as Richard, is all. No joke, just a mistake on my part.

                    "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt AntiTwitter: @DalekDave is now a follower!

                    "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
                    "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

                    E 1 Reply Last reply
                    0
                    • OriginalGriffO OriginalGriff

                      I made a mistake, and referred to Pete as Richard, is all. No joke, just a mistake on my part.

                      "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt AntiTwitter: @DalekDave is now a follower!

                      E Offline
                      E Offline
                      Exoskeletor
                      wrote on last edited by
                      #10

                      oh i though it had a deeper meaning i didn't get :)

                      1 Reply Last reply
                      0
                      • E Exoskeletor

                        Hello fellow members. Im trying to understand why my code is not catching NullReferenceException and i cant figure it out. 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()
                        {
                        {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)
                        
                        P Offline
                        P Offline
                        Pete OHanlon
                        wrote on last edited by
                        #11

                        You're making the assumption that the method that is throwing the null reference is inside your task. What's interesting is that you have failed to apply any forms of input guards to SearchMostLessViewsAsync and you're assuming you actually have values coming in. It wouldn't surprise me if the null reference you are seeing occurred in this call:

                                Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{typeof(FragmentDrawsNumbersFrequency).Name}.{nameof(SearchMostLessViewsAsync)}",
                                    new Dictionary()
                                        {
                                            {nameof(dateFrom), dateFrom.ToString()},
                                            {nameof(dateTo), dateTo.ToString()},
                                            {nameof(amountOfNumbersSelected), amountOfNumbersSelected.ToString()},
                                            {nameof(frequencyOption), frequencyOption.ToString()},
                                            {nameof(fromDrawNumber), fromDrawNumber.ToString()},
                                            {nameof(toDrawNumber), toDrawNumber.ToString()},
                                        }
                                    );
                        

                        If any of those is null, you'll get a null reference because you're calling ToString() on it. The bottom line is that you shouldn't make assumptions about where exceptions are occurring; look at the whole part of the code.

                        Advanced TypeScript Programming Projects

                        E 1 Reply Last reply
                        0
                        • P Pete OHanlon

                          You're making the assumption that the method that is throwing the null reference is inside your task. What's interesting is that you have failed to apply any forms of input guards to SearchMostLessViewsAsync and you're assuming you actually have values coming in. It wouldn't surprise me if the null reference you are seeing occurred in this call:

                                  Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{typeof(FragmentDrawsNumbersFrequency).Name}.{nameof(SearchMostLessViewsAsync)}",
                                      new Dictionary()
                                          {
                                              {nameof(dateFrom), dateFrom.ToString()},
                                              {nameof(dateTo), dateTo.ToString()},
                                              {nameof(amountOfNumbersSelected), amountOfNumbersSelected.ToString()},
                                              {nameof(frequencyOption), frequencyOption.ToString()},
                                              {nameof(fromDrawNumber), fromDrawNumber.ToString()},
                                              {nameof(toDrawNumber), toDrawNumber.ToString()},
                                          }
                                      );
                          

                          If any of those is null, you'll get a null reference because you're calling ToString() on it. The bottom line is that you shouldn't make assumptions about where exceptions are occurring; look at the whole part of the code.

                          Advanced TypeScript Programming Projects

                          E Offline
                          E Offline
                          Exoskeletor
                          wrote on last edited by
                          #12

                          hello, those values cannot ever be null from the way im setting them app and also from the crash reports they are not null, they have a value, the crash comes later. some times this code doesnt crash. some times it does. even in the devices that crash it doesnt crash always. From what i understand my biggest problem is that i dont try catch inside the task and i loose exceptions because of that. I have added a try catch inside the task and now i see that even in my device thaat never crash sometimes i get an error about ssl. The correct way is to check all those values if they are null in the beggining of the function even if by the way are initialized always have value?

                          1 Reply Last reply
                          0
                          Reply
                          • Reply as topic
                          Log in to reply
                          • Oldest to Newest
                          • Newest to Oldest
                          • Most Votes


                          • Login

                          • Don't have an account? Register

                          • Login or register to search.
                          • First post
                            Last post
                          0
                          • Categories
                          • Recent
                          • Tags
                          • Popular
                          • World
                          • Users
                          • Groups