Solved

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

Posted on 2014-10-16
6
131 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
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
PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

 
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 500 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

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Introduction This article series is supposed to shed some light on the use of IDisposable and objects that inherit from it. In essence, a more apt title for this article would be: using (IDisposable) {}. I’m just not sure how many people would ge…
This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods. Introduction In one of my applications…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…

710 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