Solved

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

Posted on 2014-10-16
6
126 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
  • 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 33

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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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 33

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Why, and when, to use Windows Workflow 1 32
which object should i use (efficiency) 5 46
New to SOAP and need some direction 10 46
designing in object programming 12 42
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…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
This Micro Tutorial will teach you how to censor certain areas of your screen. The example in this video will show a little boy's face being blurred. This will be demonstrated using Adobe Premiere Pro CS6.
Along with being a a promotional video for my three-day Annielytics Dashboard Seminor, this Micro Tutorial is an intro to Google Analytics API data.

895 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now