I have this C# windows application. Exceptions occur at times. When an exception occurs, I want to drill down on the Error Code for that exception and then fetch and print it.
Posting sample code
public void CreateSkill(int row)
{
try
{
Excel1.MWMClient.MWMServiceProxy.Skill skill = new Excel1.MWMClient.MWMServiceProxy.Skill();
skill.name = "perl";
// skill.description = "bowler";
skill.expertiseLevel = "3";
skill.ID = 1;
Console.WriteLine(skillClient.CreateSkill(skill));
Console.WriteLine(skill.ID);
ExcelRecorder(null, row);
}
catch (Exception ex)
{
ExcelRecorder(ex.Message, row);
}
finally
{
System.GC.Collect();
}
}
ExcelRecorder() is a method which prints the exception message in a cell in an excel sheet.
I want to print the exception as well as the error code in my excel sheet. How do I fetch this error code through my code?
Posting an image
Try this one:
try {
}
catch(Exception e) {
int code = e.HResult;
}
or even:
try {
}
catch (Exception e){
var Wex = e as Win32Exception;
int code = Wex.ErrorCode;
};
Related
In my project I'm trying to write code that will be nice to understand.
I currently split my data access functions in a seperate class.
What I'm trying to achieve however, is to catch the errors back to my form. I am not getting this currently and I was wondering why.
In my form I have the following code:
private void btn_Save_ItemClick(object sender, ItemClickEventArgs e)
{
if (dal.updatePerson(ObjectAfterSaving))
{
MessageBox.Show("Updated!");
}
else
{
MessageBox.Show("error");
};
}
In my dal object (derived from the DataAccess_Person class), I have the following method:
public bool updatePerson(Person p)
{
conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Database"].ConnectionString);
SqlCommand command = new SqlCommand(#"UPDATE Person
SET PersonName = #PersonName
WHERE PersonID = #PersonID", conn);
command.Parameters.Add("#PersonName", SqlDbType.VarChar).Value = p.Name
{
try
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
int a = command.ExecuteNonQuery();
conn.Close();
if (a > 0)
{
return true;
}
else
{
return false;
}
}
catch (SqlException ex)
{
ex.ToString();
return false;
}
}
}
My question is: let's say if my method falls in the catch. Will my front end (form) show it (Sql Exception for example) ? Or will i just get 'error' ? And If I will just get error, how I can improve my code to show the Exception instead of error?
A simple way is to remove the try catch from your DAL and add it to the form. For example:
private void btn_Save_ItemClick(object sender, ItemClickEventArgs e)
{
var result = "Success";
try
{
dal.updatePerson(ObjectAfterSaving);
}
catch (SqlException sqlEx)
{
result = sqlEx.Message;
}
catch (Exception ex)
{
result = ex.Message;
}
MessageBox.Show(result);
}
Just note that there's a lot of ways you can do this. My preference is to not include DAL specific exception types in my UI. Instead I may return a custom result type that has an errorcode and message and let my UI display that or generate a custom message based on the error code.
You‘ll just get „error“ in case of a SqlException. All other exceptions will crash your program if you don‘t have a global exception handler. If you want to show the error message you could introduce an out variable for the error message:
bool successful = MyMethod(out string errorMessage)
if (!successful)
{
MessageBox.Show(errorMessage);
}
public bool MyMethod(out string errorMessage)
{
errorMessage = "";
try
{
// do some stuff
return true;
}
catch(Exception ex)
{
errorMessage = ex.Message;
return false;
}
}
So I have a stack of calls. At the end of the stack an ArgumentException gets thrown. It propogates from to the last but one point where I have this code:
... Constructor(..){
try
{
this.Issuer = issuer;
this.Name = name;
this.Secret = secret;
this.totpObj = new Totp(secret, 30, 6, mode);
this.id = Guid.NewGuid().ToString();
this.mode = mode;
this.valid = true;
}
catch (System.ArgumentException e)
{
throw e; // Also tried not having this --> option B
}
catch (Exception e)
{
}
}
And this code gets called from here:
private void addButtnClick(object sender, RoutedEventArgs e)
{
try
{
...
TOTPObj totpo = new TOTPObj(af.Accname, af.Issuer, secret, stype); // <--- FAILS
...
}
catch(Exception ex) // <--- SHOULD CATCH THIS?!
{
Console.WriteLine(ex);
Environment.Exit(ERROR_FAILED_ADD_KEY);
}
}
Now if I leave the "throw" in the first section of code I get:
While I think it should be caught at the next level? (second fragment of code).
If I don't throw the exception up but just do stuff there, I never get past the "<--- FAILS" point of code block two, the thread just exits. Why is that?
I am trying to change some columns values in a DataGridView in my C# windows application, But when i try to assign the new value, i get a pop up error window which says:
DataGridView default Error Dialog
the following exception occurred in the DataGridView :...
Here is the screen shot showing this pop up window which is shown even inside a try block!
This is how I am doing it, first the gridview is populated and then i try to change some columns values , which are numbers, to show with a thousand separated numeric values. for example instead of 780000 , i get 780,000 !
private static string Test(string number)
{
try
{
gridview.DataSource = DBAPI.ExecuteSqlFunction(function, new string[] { CurrentSourceID });
//format price
foreach (DataGridViewRow row in gridview.Rows)
{
row.Cells[2].Value = GetFormattedNumber(row.Cells[2].Value.ToString().Replace(",",""));
}
}
catch (Exception ex)
{
SaveAndShowLog(ex);
}
}
public static string GetFormattedNumber(string number)
{
try
{
return string.Format("{0:N0}", Int64.Parse(number));
}
catch (Exception ex)
{
SaveAndShowLog(ex);
return number;
}
}
To hide the error message you need to handle the DataGridView.DataError event.
See sample from the link.
You could use the DataGridViewCellFormatting event to format the value, and don't try to directly replace the value with a string value since it will raise an error anyway.
private static string Test(string number)
{
try
{
gridview.DataSource = DBAPI.ExecuteSqlFunction(function, new string[] { CurrentSourceID });
gridview.CellFormatting += gridView_CellFormatting;
}
catch (Exception ex)
{
SaveAndShowLog(ex);
}
}
public static string GetFormattedNumber(string number)
{
try
{
return string.Format("{0:N0}", Int64.Parse(number));
}
catch (Exception ex)
{
SaveAndShowLog(ex);
return number;
}
}
private static void gridView_CellFormatting(object sender, System.Windows.Forms.DataGridViewCellFormattingEventArgs e)
{
if (e.ColumnIndex == 2)
{
object val = gridview.Rows[e.RowIndex].Cells[2].Value;
if ((val != null) && !object.ReferenceEquals(val, DBNull.Value))
{
e.Value = GetFormattedNumber(val.ToString().Replace(",", ""));
e.FormattingApplied = true;
}
}
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to catch exceptions
I have not really had to use try and catch exceptions. I am trying to use a try/catch to trap for potential errors. Now I am not to sure where to put the try and catch this is the code I have right now..
divide d;
private void button1_Click(object sender, EventArgs e)
{
d = new divide(int.Parse(textBox1.Text), int.Parse(textBox2.Text));
int total = d.CalculateDivision();
MessageBox.Show(total.ToString());
}
now would I put it under here with
try
{
}
catch
{
MessageBox.Show("error");
}
or would I add the try/ catch somewhere in the code.
see http://msdn.microsoft.com/en-us/library/ms173160.aspx
The try goes around the code where the exception is thrown and the value is handled. in your example:
divide d;
private void button1_Click(object sender, EventArgs e)
{
try
{
d = new divide(int.Parse(textBox1.Text), int.Parse(textBox2.Text));
int total = d.CalculateDivision();
MessageBox.Show(total.ToString());
}
catch(Exception)
{
MessageBox.Show("error");
}
}
as you can only show the total if there is no exception.
Nope, that is right ;).
Just use it like what you showed us there:
try
{
// Your Code.
}
catch (Exception ex)
{
MessageBox.Show(ex);
}
You pretty much have the answer, if an exception is thrown though you can do this to get some more information about what might have caused it:
try
{
//your code:
d = new divide(int.Parse(textBox1.Text), int.Parse(textBox2.Text));
int total = d.CalculateDivision();
MessageBox.Show(total.ToString());
}
catch (Exception ex)
{
MessageBox.Show("Error has occured! " + ex.Message);
}
Another tip for you seeing as you are learning about Exception handling is to take a look at the finally block, this will get executed whether or not there was an exception, it goes after the try and catch blocks:
finally
{
// this code will always execute, maybe do some cleanup here
}
You would do something like this:
private void button1_Click(object sender, EventArgs e)
{
try
{
d = new divide(int.Parse(textBox1.Text), int.Parse(textBox2.Text));
int total = d.CalculateDivision();
MessageBox.Show(total.ToString());
}
catch(Exception error)
{
MessageBox.Show(error.Message);
}
}
I have a C# Console app that starts in 'static int Main(string[] args)', creates an instance of 'EventRecievedProcessor' class and then calls a method on the instance:
static int Main(string[] args)
{
try
{
EventRecievedProcessor proc = new EventRecievedProcessor
if (!proc.Processs())
{
Console.Write(Type + " processing failed. Please check logs for more information.");
Log.Error("Failed to process s");
return (int)RETURNCODES.INTERNALAPPERROR;
}
}
catch (Exception ex)
{
// This is where the System.NullReferenceException from GetLatestEventInfo is currently being caught
Console.WriteLine("Exception message: " + ex.Message);
Console.WriteLine("Exception stack trace: " + ex.StackTrace);
Log.Fatal("An exception has been thrown. Message: " + ex.Message, ex);
return (int)RETURNCODES.INTERNALAPPERROR;
}
}
The instance of 'EventRecievedProcessor' grabs a collection of records and does a foreach over it. It calls a static method (GetLatestEventInfo) on the 'Event' class for each record in the collection:
public class EventRecievedProcessor
{
public bool Processs()
{
List<Event> events = DAL.GetEvents;
foreach (Event e in events)
{
try
{
EventInfo lastEvent = Eventhistory.GetLatestEventInfo(e);
}
catch (Exception ex)
{
// Log exception and continue processing in foreach loop
// This is where I want to catch the NullReferenceException from GetLatestEventInfo
Log.DebugFormat("Error with eventid " + e.EventID);
Log.Error(ex);
}
}
return true;
}
}
When the follwoing method is called, a System.NullReferenceException is thrown:
public class EventHistory
{
public static EventInfo GetLatestEventInfo(int customerCode, string premiscode)
{
EventInfo info = new EventInfo();
// Do some work here...
// This is where the NullReferenceException is being generated.
return info;
}
}
When the NullReferenceException is thrown here, I would expect the catch block in the foreach loop to catch it, log it, and then return control to the foreach loop to continue processing. Instead, the exception is being caught in the top level 'Main' method, which means the app aborts and the remaining records are not processed.
I'm at loss as to how/why the exception bypasses the first catch block. Any ideas on what I'm doing wrong here?
Adding the stack trace:
System.NullReferenceException: Object reference not set to an instance of an object.
at EventProcessor.EventHistory.GetLatestEventInfo(Event e) in C:\Dev\release6.01.100\Events\EventProcessor\EventProcessor\EventHistory.cs:line 65
at EventProcessor.Processors.EventProcessor.Process() in C:\Dev\release6.01.100\Events\EventProcessor\EventProcessor\Processors\EventProcessor.cs:line 32
at EventProcessor.Program.Main(String[] args) in C:\Dev\release6.01.100\Events\EventProcessor\EventProcessor\Program.cs:line 132
Sorry if I've munched some of the names. This is work code, so I tried to change it up a little to avoid any privacy conflicts.
It doesn't bypass anything. Look closely at your stack trace.
Try using Console.WriteLine(ex.ToString());.
You'll see that the exception is not being thrown from where you thought it was.
This simply isn't the case and here's the proof:
class Program
{
static void Main()
{
// no need of try/catch here as exceptions won't propagate to here
Looper();
}
static void Looper()
{
int processedRecords = 0;
for (int i = 0; i < 10; i++)
{
try
{
Thrower(i);
processedRecords++;
}
catch (NullReferenceException ex)
{ }
}
// prints 5 as expected
Console.WriteLine("processed {0} records", processedRecords);
}
static void Thrower(int i)
{
if (i % 2 == 0)
{
throw new NullReferenceException();
}
}
}