locked
Don't reach the Exception catch code RRS feed

  • Question

  • Hello,

    the Exception is catched but P_Ex = ex is not reached. It is skipped in debug and a unhandled Exception is thrown. Why?

       Deserialize();
      }
      catch (Exception ex)
      { P_Ex = ex; }
      
      if (P_Ex != null) { Exception_MessageDialog_Show(P_Ex); }
    }
    

    The whole class:

    using System;
    using System.Collections.Generic;
    using System.IO;
    using Windows.UI.Xaml.Controls;
    
    using System.Threading.Tasks;
    using System.Xml.Serialization;
    
    using BidListPCL;
    
    
    // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
    
    namespace BidList
    {
    
      /// <summary>
      /// An empty page that can be used on its own or navigated to within a Frame.
      /// </summary>
      public sealed partial class MainPage : Page
      {
        // NCN = Namespace_Class_Name. 
        static string NCN = "BidList.MainPage";
    
        public MainPage()
        {
          // NCN_PN = Namespace_Class_Name + Procedure_Name. 
          string NCN_PN = NCN + ".MainPage";
          Exception P_Ex = null;
    
          BidListCommon.Bid b;
    
          try
          {
            this.InitializeComponent();
    
            BidListCommon.BidListExport_Get(NCN_PN).Clear(); 
            
            int i = 1;
            while (i <= 10)
            {
              b = new BidListCommon.Bid();
    
              b.ID = (i * 10).ToString();
              b.Title = "Title" + (i * 10).ToString(); ;
              BidListCommon.BidListExport_Get(NCN_PN).Add(b);
    
              i++;
            }
    
            // Offen: Deferral anfordern!
            // In Serialize. Wirklich notwendig?
            Serialize();
    
            BidListCommon.BidListExport_Get(NCN_PN).Clear();
    
            Deserialize();
    
          }
    
          catch (Exception ex)
          { P_Ex = ex; }
    
          if (P_Ex != null) { Exception_MessageDialog_Show(P_Ex); }
        }
    
    
        async void Serialize()
        {
          string NCN_PN = NCN + ".Serialize";
    
          await Xml_Serialization.ObjectSaveToXmlFile 
               (BidListCommon.BidListExport_Get(NCN_PN), "Test.xml"); }
    
    
        async void Deserialize()
        {
          string NCN_PN = NCN + ".Deserialize";
    
          int i = 1;
          int k = 4 / (i - 1);
    
          BidListCommon.BidListExport_Set   
         (NCN_PN, 
          await Xml_Serialization.ObjectReadFromXmlFile<List<BidListCommon.Bid>>("Test.xml"));
        }
    
        private async void Exception_MessageDialog_Show(Exception ex)
        {
          var msgDlg = new Windows.UI.Popups.MessageDialog(ex.Message + "\r\n" + "\r\n" + "\r\n" +
                                                           "StackTrace:" + "\r\n" + "\r\n" +
                                                           ex.StackTrace.ToString());
          msgDlg.DefaultCommandIndex = 1;
          await msgDlg.ShowAsync();
        }
    
      }
    
    
      public static class Xml_Serialization
      {
        public static async Task<T> ObjectReadFromXmlFile<T>(string filename)
        {
          T objectFromXmlFile = default(T);
    
          var serializer = new XmlSerializer(typeof(T));
          Windows.Storage.StorageFolder folder = Windows.Storage.ApplicationData.Current.LocalFolder;
    
          Windows.Storage.StorageFile file = await folder.GetFileAsync(filename);
    
          Stream stream = await file.OpenStreamForReadAsync();
          objectFromXmlFile = (T)serializer.Deserialize(stream);
          stream.Dispose();
    
          return objectFromXmlFile;
        }
    
        public static async Task ObjectSaveToXmlFile<T>(T objectToSave, string filename)
        {
          var serializer = new XmlSerializer(typeof(T));
          Windows.Storage.StorageFolder folder = Windows.Storage.ApplicationData.Current.LocalFolder;
    
          Windows.Storage.StorageFile file = await folder.CreateFileAsync
                  (filename, Windows.Storage.CreationCollisionOption.ReplaceExisting);
    
          Stream stream = await file.OpenStreamForWriteAsync();
          using (stream)
          { serializer.Serialize(stream, objectToSave);
          }
        }
      }
    
    }

    Saturday, October 24, 2015 2:44 PM

Answers

  • I don't see why it would not get hit.  Did you put a breakpoint on that line of code?   I would not recommend using async functions which are void they don't always behave as you expect. Your function should return a value so it runs all the code.  

    Are you sure the stack trace is not null?

    Why is the InitializeComponent call in a try catch block?

     What are you getting in the unhandled exception event?

    • Marked as answer by Markus222 Tuesday, November 3, 2015 2:06 PM
    Saturday, October 24, 2015 4:27 PM
  • Hook up Unobserved Exception handler, see if that's catching it as I suspect is the lack of async await in the caller

    http://pauliom.wordpress.com

    • Marked as answer by Markus222 Tuesday, November 3, 2015 2:07 PM
    Saturday, October 24, 2015 10:58 PM

All replies

  • I don't see why it would not get hit.  Did you put a breakpoint on that line of code?   I would not recommend using async functions which are void they don't always behave as you expect. Your function should return a value so it runs all the code.  

    Are you sure the stack trace is not null?

    Why is the InitializeComponent call in a try catch block?

     What are you getting in the unhandled exception event?

    • Marked as answer by Markus222 Tuesday, November 3, 2015 2:06 PM
    Saturday, October 24, 2015 4:27 PM
  • Hello Ken,

    you wrote:

    >> I don't see why it would not get hit. Did you put a breakpoint on that line of code?

    No. After your answer i set breakpoints and i saw that the catch clause

    catch (Exception ex)

      { P_Ex = ex; }

    was just skipped. Not reached.



    >> Are you sure the stack trace is not null?

    I get no exception. No stacktrace.



    >> why is the InitializeComponent call in a try catch block?



    Thought its part of the code and put in in there. I would not change InitalizeComponent by myself.

    Changed it to

        public MainPage()

        {

          this.InitializeComponent();

    result is the same.



    >> What are you getting in the unhandled exception event?



    In Deserialize

    An exception of type 'System.DivideByZeroException' occurred in BidList.exe but was not handled in user code

    Additional information: Attempted to divide by zero.

    After pressing F5 this code is reached

        partial class App : global::Windows.UI.Xaml.Application

        {

    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 14.0.0.0")]

            private bool _contentLoaded;

            /// <summary>

            /// InitializeComponent()

            /// </summary>

            [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 14.0.0.0")]

            [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]

            public void InitializeComponent()

             {

                if (_contentLoaded)

                    return;

                _contentLoaded = true;

    #if DEBUG && !DISABLE_XAML_GENERATED_BINDING_DEBUG_OUTPUT

                DebugSettings.BindingFailed += (sender, args) =>

                {

                    global::System.Diagnostics.Debug.WriteLine(args.Message);

                };

    #endif

    #if DEBUG && !DISABLE_XAML_GENERATED_BREAK_ON_UNHANDLED_EXCEPTION

                UnhandledException += (sender, e) =>

                {

                    if (global::System.Diagnostics.Debugger.IsAttached) global::System.Diagnostics.Debugger.Break();

                };

    #endif

            }

        }

    }

    > I would not recommend using async functions which are void they don't always behave as you

    > expect. Your function should return a value so it runs all the code.



    Hm, i hope that this is the point. But how i can make it a task. The classcode you see. Change it to awaiting tasks?



    Thank you, if you like to see the whole test solution. it is very little code, send a  short with your mail address to ks600@gmx.de


    Saturday, October 24, 2015 6:14 PM
  • Hook up Unobserved Exception handler, see if that's catching it as I suspect is the lack of async await in the caller

    http://pauliom.wordpress.com

    • Marked as answer by Markus222 Tuesday, November 3, 2015 2:07 PM
    Saturday, October 24, 2015 10:58 PM
  • Hello Markus222,

    I just tested your code with simplified code and its work correct and shows me the dialog message. I don't see any reason why it would hit the catch block but don't set the P_Ex exception.

    	public MainPage()
    		{
    			this.InitializeComponent();
    
    			Exception P_Ex = null;
    
    
    			try
    			{
    				this.InitializeComponent();
    
    				throw new Exception("test");
    			}
    
    			catch (Exception ex)
    			{
    				P_Ex = ex;
    			}
    
    			if (P_Ex != null) { Exception_MessageDialog_Show(P_Ex); }
    
    		}

     You need to check weather the function inside try catch. Have another try catch in them or not. If the inner function also have try catch for them then they would catch the exception in the inner function and the outer flow would go on and the outer catch would not catch it unless you manually throw it.  

    With Regards,

    Krunal Parekh


    Thanks MSDN Community Support Please remember to Mark as Answer the responses that resolved your issue. It is a common way to recognize those who have helped you, and makes it easier for other visitors to find the resolution later.

    Monday, October 26, 2015 7:13 AM
  • OK. Thank you. The thing is the asynchronous execution of the code. When i change the code to this:

       public MainPage()
        {
          this.InitializeComponent();
        }
    
        /*****************************************************************************
         * Events.
         ******************************************************************************/
    
        private async void button1_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
          // NCN_PN = Namespace_Class_Name + Procedure_Name. 
          string NCN_PN = NCN + ".button1_Click";
          Exception P_Ex = null;
    
          BidListCommon.Bid b;
    
          try
          {
    
            BidListCommon.BidListExport_Get(NCN_PN).Clear();
    
            int i = 1;
            while (i <= 10)
            {
              b = new BidListCommon.Bid();
    
              b.ID = (i * 10).ToString();
              b.Title = "Title" + (i * 10).ToString(); ;
              BidListCommon.BidListExport_Get(NCN_PN).Add(b);
    
              i++;
            }
    
            // Offen: Deferral anfordern!
            // In Serialize. Wirklich notwendig?
            await Serialize();
    
            BidListCommon.BidListExport_Get(NCN_PN).Clear();
    
            await Deserialize();
    
          }
    
          catch (Exception ex)
          { P_Ex = ex; }
    
          if (P_Ex != null) { Exception_MessageDialog_Show(P_Ex); }
    
        }

    the exception message is shown and the serialization is ok. But how can i do this when i need the code in the constructor??? No button which click event i can mark as async. The constructor can't have async and no await.

    The whole class:

    using System;
    using System.Collections.Generic;
    using System.IO;
    using Windows.UI.Xaml.Controls;
    
    using System.Threading.Tasks;
    using System.Xml.Serialization;
    
    using BidListPCL;
    
    
    // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
      
    namespace BidList
    {
    
      /// <summary>
      /// An empty page that can be used on its own or navigated to within a Frame.
      /// </summary>
      public sealed partial class MainPage : Page
      {
        // NCN = Namespace_Class_Name. 
        static string NCN = "BidList.MainPage";
    
        // Offen: Private varaiblen wo?
    
        /*****************************************************************************
         * Events.
        ******************************************************************************/
    
        /*****************************************************************************
         * Properties.
        ******************************************************************************/
    
        /*****************************************************************************
         * Constructors.
        ******************************************************************************/
    
        public MainPage()
        {
          this.InitializeComponent();
        }
    
        /*****************************************************************************
         * Events.
         ******************************************************************************/
    
        private async void button1_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
          // NCN_PN = Namespace_Class_Name + Procedure_Name. 
          string NCN_PN = NCN + ".button1_Click";
          Exception P_Ex = null;
    
          BidListCommon.Bid b;
    
          try
          {
    
            BidListCommon.BidListExport_Get(NCN_PN).Clear();
    
            int i = 1;
            while (i <= 10)
            {
              b = new BidListCommon.Bid();
    
              b.ID = (i * 10).ToString();
              b.Title = "Title" + (i * 10).ToString(); ;
              BidListCommon.BidListExport_Get(NCN_PN).Add(b);
    
              i++;
            }
    
            // Offen: Deferral anfordern!
            // In Serialize. Wirklich notwendig?
            await Serialize();
    
            BidListCommon.BidListExport_Get(NCN_PN).Clear();
    
            await Deserialize();
    
          }
    
          catch (Exception ex)
          { P_Ex = ex; }
    
          if (P_Ex != null) { Exception_MessageDialog_Show(P_Ex); }
    
        }
    
    
        /*****************************************************************************
         * Private Procedures.
        ******************************************************************************/
    
        async Task Serialize()
        {
          string NCN_PN = NCN + ".Serialize";
    
          await Xml_Serialization.ObjectSaveToXmlFile 
               (BidListCommon.BidListExport_Get(NCN_PN), "Test.xml"); }
    
    
        async Task Deserialize()
        {
          string NCN_PN = NCN + ".Deserialize";
    
          BidListCommon.BidListExport_Set   
         (NCN_PN, 
          await Xml_Serialization.ObjectReadFromXmlFile<List<BidListCommon.Bid>>("Test.xml"));
    
          }
    
        private async void Exception_MessageDialog_Show(Exception ex)
        {
          var msgDlg = new Windows.UI.Popups.MessageDialog(ex.Message + "\r\n" + "\r\n" + "\r\n" +
                                                           "StackTrace:" + "\r\n" + "\r\n" +
                                                           ex.StackTrace.ToString());
          msgDlg.DefaultCommandIndex = 1;
          await msgDlg.ShowAsync();
        }
    
      }
    
    
      public static class Xml_Serialization
      {
        public static async Task<T> ObjectReadFromXmlFile<T>(string filename)
        {
          T objectFromXmlFile = default(T);
    
    
          int i = 1;
          int k = 4 / (i - 1);
    
    
          var serializer = new XmlSerializer(typeof(T));
          Windows.Storage.StorageFolder folder = Windows.Storage.ApplicationData.Current.LocalFolder;
    
          Windows.Storage.StorageFile file = await folder.GetFileAsync(filename);
    
          Stream stream = await file.OpenStreamForReadAsync();
          objectFromXmlFile = (T)serializer.Deserialize(stream);
          stream.Dispose();
    
          return objectFromXmlFile;
        }
    
        public static async Task ObjectSaveToXmlFile<T>(T objectToSave, string filename)
        {
          var serializer = new XmlSerializer(typeof(T));
          Windows.Storage.StorageFolder folder = Windows.Storage.ApplicationData.Current.LocalFolder;
    
          Windows.Storage.StorageFile file = await folder.CreateFileAsync
                  (filename, Windows.Storage.CreationCollisionOption.ReplaceExisting);
    
          Stream stream = await file.OpenStreamForWriteAsync();
          using (stream)
          { serializer.Serialize(stream, objectToSave);
          }
        }
      }
    
    }

    BidListCommon.cs:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    using System.Diagnostics;
    
    namespace BidListPCL
    {
      public class BidListCommon
      {
        // NCN = Namespace_Class_Name. 
        static string NCN = "BidListPCL.BidListCommon";
    
        public class Bid
        {
          public string ID { get; set; }
          public string Title { get; set; }
    
          public Bid()
          {
            ID = "";
            Title = "";
          }
        }
    
    
        private static List<Bid> bidListExport = new List<Bid>();
        public static List<Bid> BidListExport_Get(string P_Caller_N)
        {
          // NCN_PN = Namespace_Class_Name + Procedure_Name. 
          string NCN_PN = NCN + ".BidListExport_Get";
    
          Debug.Assert(P_Caller_N == "BidList.MainPage.button1_Click"
                       || P_Caller_N == "BidList.MainPage.Serialize",
                       NCN_PN + " called from wrong procedure: " + P_Caller_N);
    
          return bidListExport;
        }
    
        public static void BidListExport_Set(string P_Caller_N, 
                                             List<Bid> pBidListExport)
        {
          string NCN_PN = NCN + ".BidListExport_Set";
    
          Debug.Assert(P_Caller_N == "BidList.MainPage.Deserialize",
                       NCN_PN + " called from wrong procedure: " + P_Caller_N);
    
          try
          { bidListExport = pBidListExport;
            int i = 1;
            int k = 4/(i - 1);
          }
          catch (Exception ex)
          { throw; }
    
    
          
        }
    
      }
    }



    • Edited by Markus222 Monday, October 26, 2015 11:51 AM
    Monday, October 26, 2015 11:48 AM
  • Normally you want to avoid to putting stuff in the constructor like that. If you can, I would run code like Task.Run(async () => { try..catch -> ... your new version of current code  }.

    It means the constructor will finish before the task is run, but I'm guessing that will be fine?


    http://pauliom.wordpress.com


    • Edited by pkr2000 Monday, October 26, 2015 1:42 PM
    • Proposed as answer by Krunal Parekh Tuesday, November 3, 2015 9:48 AM
    Monday, October 26, 2015 1:41 PM
  • if you put the code some where I can download it I will look at it tonight
    Monday, October 26, 2015 2:22 PM
  • Hello pkr,

    > Normally you want to avoid to putting stuff in the constructor like that. If you can, I would run code like
    > Task.Run(async () => { try..catch -> ... your new version of current code  }.
    > It means the constructor will finish before the task is run, but I'm guessing that will be fine?

    i think yes. but the exception handling and the showing of the message then? How to do this? Just with the code above? Please show an example with the Call of Deserialize and the Error Message showing.

    Monday, October 26, 2015 3:21 PM
  • Hello Ken,

    thank you. This is nice but i think not necessary. I think i could put the call of the Deserialize of the BidList in some MainPage Event. The question that remains only is how to put async calls in class constructors with error handling that shows the message and/or logs it.

    Monday, October 26, 2015 3:29 PM
  • You put the try catch inside the task run and handle at as you would in your non-constructor example.

    http://pauliom.wordpress.com


    • Edited by pkr2000 Monday, October 26, 2015 3:42 PM
    Monday, October 26, 2015 3:42 PM
  • when i try this the message when showing the Message Dialog is:

    An exception of type 'System.Exception' occurred in mscorlib.ni.dll but was not handled in user code

    WinRT information: Diese API muss aus einem Thread mit „CoreWindow“ aufgerufen werden, oder es muss explizit ein Fenster festgelegt worden sein.

    Additional information: Ungültiges Fensterhandle

    try to translate it:
    WinRT information: This API must be called from a thread with "Core Window", or it must be explicitly a window have been fixed.

    Additional information: Invalid window handle

    <textarea aria-hidden="true" autocapitalize="off" autocomplete="off" autocorrect="off" class="goog-textarea" dir="ltr" id="contribute-target" name="edit-text" rows="1" spellcheck="false" style="height:105px;padding-right:20px;display:none;-ms-overflow-x:auto;-ms-overflow-y:hidden;box-sizing:border-box;" tabindex="0" wrap="SOFT">necessary</textarea>

        public MainPage()
        {
          this.InitializeComponent();
    
          Task.Run(async () =>
          {
    
    
            // NCN_PN = Namespace_Class_Name + Procedure_Name. 
            string NCN_PN = NCN + ".MainPage";
            Exception P_Ex = null;
    
            BidListCommon.Bid b;
    
            try
            {
              await Deserialize();
    
              // Just for a breakpoint to look.
              int k = 1;
            }
    
            catch (Exception ex)
            { P_Ex = ex; }
    
            if (P_Ex != null) { Exception_MessageDialog_Show(P_Ex); }
    
          });
        }
    


    Monday, October 26, 2015 4:36 PM
  • I think it is to much what Microsoft does. They want to make programming easy but they make it not possible to understand any more. you don't know what the compiler and the runtime do. and how get the exception from one side to the other?...

    Monday, October 26, 2015 4:56 PM
  • Looks like your are trying to show a message dlg but you're now off the ui thread, the error isn't too bad. You need to use a dispatcher to invoke the msg on the ui thread

    http://pauliom.wordpress.com

    • Proposed as answer by Krunal Parekh Tuesday, November 3, 2015 9:49 AM
    Monday, October 26, 2015 11:08 PM