Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

I'm wondering why I don't get an error on this Windows Form C#

Posted on 2014-10-16
6
Medium Priority
?
134 Views
Last Modified: 2014-10-16
On this form, if I get an error in the catch block, I would expect an "unhandled exception" issue.  This is important because it's being run from Task Scheduler and we're not being notfied of the failure.  Because of the finally block the program exits gracefully.  Without the finally block the program just hangs.  Why am I not getting the unhandled exception?

    public partial class frmRunProcesses : Form
    {
        private string _DefectPath = "";

        public frmRunProcesses()
        {
            InitializeComponent();
        }

        private void frmRunProcesses_Load(object sender, EventArgs e)
        {
            try
            {
             Note:  I added these throws in just to test error trapping
                throw new Exception("can't write");

                this.GetSettings();

                Processing p = new Processing(Application.StartupPath + @"\NPSEDIConfig.xml");


                if (!p.ProcessAll("scheduled"))
                {
                    throw new Exception("At frmRunProcesses_Load:\n\r\n\r" + p.ErrMess);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("can't write");
                if (this._DefectPath.Trim().Length != 0)
                {
                    this.WriteMessage('E', ex.Message, this._DefectPath);
                }
                else
                {
                    this.WriteMessage('E', ex.Message, Application.StartupPath + @"\");
                }
            }
            //finally
            //{
            //    Application.Exit();
            //}

        }

        private void GetSettings()
        {
            try
            {
                PkgSettings ps = new PkgSettings(Application.StartupPath + @"\Config.xml");
                if (ps.GetSettings() == 0)
                {
                    this._DefectPath = ps.DefectPath;
                }
                else
                {
                    throw new Exception("Cannot Get Settings:\n\r\n\r" + ps.ErrMessage);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("At GetSettings:\n\r\n\r" + ex.Message);
            }
        }

        private void WriteMessage(char mType, string Message, string wPath)
        {
            StreamWriter sw = new StreamWriter(wPath + "ScheduledRunErrLog.txt", true);
            sw.WriteLine(DateTime.Now.Year.ToString()
                + DateTime.Now.Month.ToString().PadLeft(2, '0') + " "
                + DateTime.Now.Day.ToString().PadLeft(2, '0') + " "
                + DateTime.Now.Hour.ToString().PadLeft(2, '0') + " "
                + DateTime.Now.Minute.ToString().PadLeft(2, '0') + " "
                + DateTime.Now.Second.ToString().PadLeft(2, '0') + "| "
                + mType.ToString() + ": " + Message);
            sw.Flush();
            sw.Close();
        }
    }
0
Comment
Question by:g_johnson
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
6 Comments
 
LVL 27

Expert Comment

by:Sammy Ageil
ID: 40385311
Both exception and finally clause are reached
When you run this code you will get a message box with "Exception thrown Something went wrong!" then another messagebox with "Finally Reached"

            try
            {
                throw new Exception("Something went wrong!");

                DoStuff("Move");


            }
            
           
            catch (Exception ex)
            {

            MessageBox.Show(String.Format("Exception thrown {0}", ex.Message));
            }
          

            finally
            {
                MessageBox.Show("Finally Reached");
            }

Open in new window

0
 
LVL 4

Author Comment

by:g_johnson
ID: 40385347
Sammy -- thanks.  That's is what's happening, of course.  But, when I have an exception in the Catch block, shouldn't I have a fatal error?
0
 
LVL 34

Expert Comment

by:it_saige
ID: 40385365
The only exception that is never captured by the running assembly is the StackOverflowException.  All other exceptions should be catchable (even though in certain situations; catching exceptions seems to be quirky; e.g. External component exceptions do not always get caught.)

The best way that I have found to combat this is to use the Application.ThreadException and AppDomain.CurrentDomain.UnhandledException events to try and capture any untrapped exceptions; e.g. -

Program.cs
using System;
using System.Windows.Forms;

namespace ExceptionExample
{
	static class Program
	{
		static Program()
		{
			Application.ThreadException += OnThreadException;
			AppDomain.CurrentDomain.UnhandledException += OnApplicationUnhandledException;
		}

		/// <summary>The main entry point for the application.</summary>
		[STAThread]
		static void Main()
		{
			new frmRunProcesses();
			return;
		}

		#region Event Handler Methods
		private static void OnThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
		{
			// Write your log message here.  You access the exception from the e Argument:
			// e.Exception
		}

		private static void OnApplicationUnhandledException(object sender, UnhandledExceptionEventArgs e)
		{
			if (e.IsTerminating)
			{
				object o = e.ExceptionObject;
				// o in this case now represents an exception object, not that same as an exception class.
				// string.Format("{0}", o);
				// o.ToString();
			}
		}
		#endregion
	}
}

Open in new window


Ultimately, this raises the question.  Are you certain that you are excepting and how do you know this (I assume it's just because of the application hanging)?

-saige-
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 4

Author Comment

by:g_johnson
ID: 40385387
it_saige -- That's a little over my head, unfortunately!  but, I'll try to answer your question.  As presented, when I hit the first Throw, it does indeed take me to the Catch.  Then, inside the Catch, I do another Throw.  That is unhandled and this is where I would expect the app to end ungracefully with a "exception not handled" error.  Instead, if the finally block is not active it just hangs.  If the finally block is active the program ends.

The only reason this matters is that we are having problems running it from Task Scheduler, and we would like to see Task Scheduler report the error.  Since the program ends "gracefully" (with the finally block in place), Task Scheduler just reports a normal end to the process.
0
 
LVL 34

Accepted Solution

by:
it_saige earned 2000 total points
ID: 40385422
Let me see if I can explain what is happening here.  In a standard Try...Catch block, you try to complete the task and catch any problems.  How you handle those problems is up to you (rethrow the exception, throw a new exception, write to a log file or [the oft dreaded] do nothing).  When you handle the problem with a new throw or rethrow, it is up to the calling method (in this case, since it is in the load event, the calling method is most likely main) to handle the exception since the exception is bubbled up to it.

Most of the time, Main does not have a Try...Catch block, so what you get presented with instead is:Capture.JPG
If this running as a scheduled task and the user is not logged in, then you do not get a  message box because the task scheduler is a service and does not interact with the desktop, so your application hangs because it is waiting for someone to make a choice ('Debug' or 'Close program' in this case).

Which is where  the events in the Program.cs would come into play.  They would catch the exceptions and log them.

When you add ...Finally to the Try...Catch equation, the finally always processes.  So your finally is basically telling the application to stop running, which closes the above mention window.

-saige-
0
 
LVL 4

Author Closing Comment

by:g_johnson
ID: 40385437
Perfect!  Thank you.  That's what I needed to understand.
0

Featured Post

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: Najam
Having new technologies does not mean they will completely replace old components.  Recently I had to create WCF that will be called by VB6 component.  Here I will describe what steps one should follow while doing so, please feel free to post any qu…
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
Video by: ITPro.TV
In this episode Don builds upon the troubleshooting techniques by demonstrating how to properly monitor a vSphere deployment to detect problems before they occur. He begins the show using tools found within the vSphere suite as ends the show demonst…
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…
Suggested Courses

722 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question