Catch ALL errors not just individual buttons [duplicate] - c#

This question already has answers here:
How can I make something that catches all 'unhandled' exceptions in a WinForms application?
(4 answers)
Closed 9 years ago.
I want a general catch all error that works for all functions. Right now I have a try and catch for each individual button click for specific events. I need a catch all error for my whole program which includes all button clicks that can catch any individual exception I might have missed. Can someone please point me in the right direction
My current code:
private void Show_btn_Click(object sender, EventArgs e)
{
try
{
//do something
}
catch (Exception error)
{
outputLOG.Append(error.ToString());
{
}
private void Submit_btn_Click(object sender, EventArgs e)
{
try
{
//do something
}
catch (Exception error)
{
outputLOG.Append(error.ToString());
}
}
Goal: I want to catch ALL buttons just in case I missed individual exceptions
EDIT: I am using winforms

Add these lines before entering the first form of your application (usually in the main method in program.cs)
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
......
private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
string msg = e.Exception.Message;
if (e.Exception.InnerException != null)
{
msg = msg + "\r\nPrevious error:" + e.Exception.InnerException.Message;
}
msg = msg + "\r\n\r\nDo you wish to continue with the application?";
DialogResult dr = MessageBox.Show(msg, "Exception", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dr == DialogResult.No) Application.Exit();
}
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Exception ex = e.ExceptionObject as Exception;
if (ex != null)
{
string msg = ex.Message;
if (ex.InnerException != null)
{
msg = msg + "\r\nPrevious error :" + ex.InnerException.Message;
}
msg = msg + "\r\n\r\nIt is not possible to continue. Contact support service!";
MessageBox.Show(msg, "Fatal Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

Related

trying to make a textbox populate a variable that changes every three seconds

I am trying to make a text box in a WPF C# application populate a text box from a variable gathered from an external database using WCF and having little luck. Currently the text box states ScoreBoardClientTest.FeedServiceAgent instead of the value of agentsavailable. I was able to make this exact same code work in a console application when using this line of code inside of OnMessageReceived
console.writeline(e.cmsdata.skill.agentsavailable.tostring());
so I assumed I could do something similar here.
any help understanding where I'm going wrong would be great.
DisplayNumber is the name of the textbox.
public void TextBlock_Loaded(object sender, EventArgs e)
{
using (var data = new FeedServiceAgent())
{
data.MessageReceived += OnMessageReceived;
data.Subscribe("92", 3);
DisplayNumber.Text = data.ToString();
}
}
public static void OnMessageReceived(object sender, MessageReceivedEventArgs e)
{
try
{
if (e == null)
return;
if (e.CmsData == null)
{
e.CmsData.Skill.AgentsAvailable.ToString();
}
// if (!String.IsNullOrEmpty(e.Message))
// Console.WriteLine(e.Message);
}
catch (Exception ex)
{
// logger.Error(" Exception " + ex);
// throw ex;
}
}
Edit
Changed:
DisplayNumber.Text =e.CmsData.Skill.AgentsAvailable.ToString();
to:
Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() => { DisplayNumber.Text = e.CmsData.Skill.AgentsAvailable.ToString() ; }
This will handle multithreaded calls. You might have to add a using System.Threading statement for the DispatcherPriority enum
EndEdit
It is still unclear how to get from the data of Type FeedServiceAgent to a Skill.AgentsAvailable property in your Loaded event handler. We need more information on how to make that navigation. Is the assignment even necessary in the Loaded handler? I've marked the location in the code below.
I've also made what appears to be the necessary changes to the message handler method.
public void TextBlock_Loaded(object sender, EventArgs e)
{
using (var data = new FeedServiceAgent())
{
data.MessageReceived += OnMessageReceived;
data.Subscribe("92", 3);
//DisplayNumber.Text = data.ToString();
//Is this assignment even necessary?
DisplayNumber.Text = /*Still unclear what goes here because we don't know what how to get from `data` to `Skill`*/
}
}
public static void OnMessageReceived(object sender, MessageReceivedEventArgs e)
{
try
{
if (e == null)
return;
if (e.CmsData == null)
{
//e.CmsData.Skill.AgentsAvailable.ToString();
Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() => { DisplayNumber.Text = e.CmsData.Skill.AgentsAvailable.ToString() ; }));
}
// if (!String.IsNullOrEmpty(e.Message))
// Console.WriteLine(e.Message);
}
catch (Exception ex)
{
// logger.Error(" Exception " + ex);
// throw ex;
}
}

dataGridView default error dialog handle

I am trying to hide default datagridview error dialog.
I put in the code this event handler:
this.dataGridView2.DataError += new System.Windows.Forms.DataGridViewDataErrorEventHandler(dataGridView2_DataError);
private void dataGridView2_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
//empty so it doesn't show anything
}
But still when i try this and leave datagridview cell empty ( delete everything from it), it show me dialog box with error.
Screenshot of error:
Try to Handle and Cancel the event:
private void dataGridView2_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
e.Cancel = true;
}
Also, subscribe to the event in InitializeComponent()
private void InitializeComponent()
{
//...
this.dataGridView.DataError += new System.Windows.Forms.DataGridViewDataErrorEventHandler(this.dataGridView2_DataError);
}
try to use this code to handle the event:
private void dataGridView2_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
e.Cancel = true;
}
Try the next code , it's work!
private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
try
{
//To handle 'ConstraintException' default error dialog (for example, unique value)
if ((e.Exception) is System.Data.ConstraintException)
{
// ErrorText glyphs show
dataGridView1.Rows[e.RowIndex].ErrorText = "must be unique value";
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = "must be unique value";
//...or MessageBox show
MessageBox.Show(e.Exception.Message, "Error ConstraintException",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
//Suppress a ConstraintException
e.ThrowException = false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "ERROR: dataGridView1_DataError",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

MessageBoxButton.YesNo error when press NO

When I press Disconnect button in form, is asking me if Yes or No. I press No, but then I can do only one action in program because after that, it crashes. Why?
private void button3_Click(object sender, EventArgs e)
{
DialogResult dialres = MessageBox.Show("Sunteti sigur ca vreti sa va deconectati?",
"Atentie!", MessageBoxButtons.YesNo);
if (dialres == DialogResult.OK)
{
try
{
_conn.Close();
_conn = null;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
button1.Enabled = true;
stopbut();
}
else if (dialres == DialogResult.No)
{
return;
}
}
Your first if will never be true, because you are testing for OK, not for YES. In your second if you have a return statement, so your method will finish. So not really sure what else you expected?
when you press 'No' nothing change so there should be another reason for crash, maybe that one action you do cause the crash. when you do any action your program crash or a specific one?
Edit: put the code of action that cause the crash
sorry everyone, i should comment not answer :( but i cant comment because commenting needs 50 reputations and i have only 39
and your code maybe more efficient like this:
private void button3_Click(object sender, EventArgs e)
{
DialogResult dialres =;
if ( MessageBox.Show("Sunteti sigur ca vreti sa va deconectati?",
"Atentie!", MessageBoxButtons.YesNo) == DialogResult.No) return;
//when it ain't 'No' it is definitely 'Yes'
try
{
_conn.Close();
_conn = null;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
button1.Enabled = true;
stopbut();
}
else if (dialres == DialogResult.No)
{
return;
}
}

BackgroundWorker capture error

I've been trying to follow this MSDN example, and using the code below. However, e.Error is ALWAYS null in RunWorkerCompleted even when an error does occur in SomeMethod();
private void WorkerDoWork(object sender, DoWorkEventArgs e)
{
getMethod = SomeMethod();
}
private void Worker_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
var result = ModernDialog.ShowMessage("Error occurred.... " +
e.Result, "ErrorTitle", MessageBoxButton.OK);
}
else if (e.Cancelled)
{
}
Else
{
}
}
Can anyone see what I'm doing wrong?
I can get around it by doing the following but I don't really understand why the example in MSDN is not working for me?
private void WorkerDoWork(object sender, DoWorkEventArgs e)
{
try
{
getMethod = SomeMethod();
}
catch(Exception ex)
{
e.Result = ex;
}
}
private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Result is Exception)
{
var result = ModernDialog.ShowMessage("Error occurred.... " + e.Result, "ErrorTitle", MessageBoxButton.OK);
}
//etc
}
Also, using the second method I can't access the .Message from e.Result. For example, in WorkerDoWork I can use ex.Message
Edit: I've setup the worker to create it's own error and I still get e.Error == null. The variable displayed is a bit faint as CTRL+PrtSc makes it fade
I think the problem is your empty exception block in emailWorkerDoWork(). For the result to be an exception you can't catch the exceptions in your background worker.
So something like this should give you the desired result:
private void emailWorkerDoWork(object sender, DoWorkEventArgs e)
{
int value = 1 / int.Parse("0");
}
I found another SO answer that confirms my suspicion and provides a MSFT reference here.

C# Catching exception

Am quite new to this, so please help.
I have the following image clicked code.
However, an error will occur if the user does not click on a image.
How can i do an error check to catch that if the user does not click on an image and attempts to proceed, a messagebox will display notifying him to click an image.
Error msg: The error is at "ListViewItem selectedItem = listView1.SelectedItems[0] Error Msg: Invalid Argument = Value of '0' is not valid for 'index
Below is my code:
private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
int i = e.ProgressPercentage;
object fbUserObject = e.UserState;
if (fbUserObject is DataRow)
{
var fbUser = fbUserObject as DataRow;
var item = new ListViewItem(fbUser["friend_name"].ToString());
item.Tag = fbUser["friend_id"];
item.ImageIndex = i;
listView1.Items.Add(item);
}
else if (fbUserObject is Image)
{
imageList.Images.Add(fbUserObject as Image);
}
}
private void imageClicked(Object sender, System.EventArgs e)
{
ListViewItem selectedItem = listView1.SelectedItems[0];
selectedFBId = selectedItem.Tag as string;
selectedFBName = selectedItem.Text;
DialogResult dialogA = MessageBox.Show("Analyse employee data?", "SOC", MessageBoxButtons.YesNo);
if (dialogA == DialogResult.Yes)
{
TargetEmployee.Text = "Selected Target: " + selectedFBName;
pf.Show();
ThreadPool.QueueUserWorkItem(LoadUserDetails);
}
}
You shouldn't catch an exception, you should handle when there aren't any selected items
if(listView1.SelectedItems.Count == 0)
{
MessageBox.Show(this, "No image");
return;
}
Exceptions should be caught when you don't expect something to happen, if you are aware of a possible issue, you should handle that before it becomes an issue
change your code like this
private void imageClicked(Object sender, System.EventArgs e)
{
if(listView1.SelectedItems.Count < 1)
return;
ListViewItem selectedItem = listView1.SelectedItems[0];
selectedFBId = selectedItem.Tag as string;
selectedFBName = selectedItem.Text;
DialogResult dialogA = MessageBox.Show("Analyse employee data?", "SOC", MessageBoxButtons.YesNo);
if (dialogA == DialogResult.Yes)
{
TargetEmployee.Text = "Selected Target: " + selectedFBName;
pf.Show();
ThreadPool.QueueUserWorkItem(LoadUserDetails);
}
}
You can use a try { } catch { } statement for your error handling.
Once you locate the line of code that generates an exception, you can wrap it into a block like this
try
{
int a = int.Parse("pedantic"); // This throws an error because you cannot convert
}
catch (Exception e)
{
// Handle your error here instead of crashing your program
}

Categories