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?
Related
I am catching an exception and processing it.
Somewhere up the call tree, I am doing the same.
Once I process my exception at the child level, I want to also go ahead and invoke the exception handler, wherever it is, somewhere up the call tree.
For that, I thought I would do run the throw again.
But instead of breaking somewhere up the call tree, it is breaking in the place where I am doing the throw and crashing, at this line:
throw new Exception("Cannot Write Header Row to Database " + Msg);
code:
public static void NewHeaderRow(string FILE_REV_NUMBER, DateTime FILE_CREATE_DATE, string EDC_DUNS_NUMBER, int RunId)
{
SqlConnection connection = null;
try
{
connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DbConn"].ToString());
connection.Open();
SqlCommand com;
com = new SqlCommand("dbo.INSERT_PPL_HEADER", connection);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.Add(new SqlParameter("#FILE_REV_NUMBER", FILE_REV_NUMBER));
com.Parameters.Add(new SqlParameter("#FILE_CREATE_DATE", FILE_CREATE_DATE));
com.Parameters.Add(new SqlParameter("#EDC_DUNS_NUMBER", EDC_DUNS_NUMBER));
com.Parameters.Add(new SqlParameter("#RunId", RunId));
if (com.Connection.State == ConnectionState.Closed) com.Connection.Open();
com.ExecuteNonQuery();
}
catch (Exception e)
{
string Msg;
Msg = "Encountered unexpected program issue. Please contact your program administator. Error details...";
Msg = Msg + System.Environment.NewLine;
Msg = Msg + System.Environment.NewLine;
Msg = Msg + e.ToString();
Msg = Msg + System.Environment.NewLine;
Msg = Msg + System.Environment.NewLine;
Msg = Msg + e.Message;
throw new Exception("Cannot Write Header Row to Database " + Msg);
}
finally
{
if (connection == null) { } else connection.Close();
}
}
Try just using the throw keyword, instead of building a new exception.
https://stackoverflow.com/a/2999314/5145250
To add additional information to the exception warp it in another exception object and pass the original exception as argument with new message to keep the original stack trace in inner exception.
throw new Exception("Cannot Write Header Row to Database " + Msg, e);
At some top level you should handle global exceptions to avoid crashing.
The way I was finally able to pin point the problem was to extremely simplify my code so as to be able to see the problem clearly. I just copied my solution to a new location, and gutted out all the non-essential stuff -- stuff I knew was not going to be important for the purposes of troubleshooting.... Very effective way of troubleshooting difficult problems that are hard to trace.... Here is what I ended up with (the simple code).
I was not catching general exception in the code that calls NewHeaderRow.
I was catching System.IO exception.
So, because code had nowhere to go, it crashed....
It is very hard for the eyes to catch this error and also difficult to trace.
private void button1_Click(object sender, EventArgs e)
{
LoadFile();
}
private static int ProcessHeaderRow(string line)
{
int LoadRunNumber = 0;
try
{
//some complex logic was here; error occurs here, so I throw an exception....
throw new Exception("An Error Occurs -- Process Header Row Try block");
}
catch (CustomExceptionNoMessage e)
{
throw new CustomExceptionNoMessage(e.Message);
}
catch (Exception e)
{
//Process the exception, then rethrow, for calling code to also process the exception....
//problem is here...XXXXXXXXXXXXXXXXXX
throw new Exception(e.Message); //crashes
}
return LoadRunNumber;
}
public static bool LoadFile()
{
int RunId = 0;
try
{
RunId = ProcessHeaderRow("10~~happy~007909427AC");
MessageBox.Show("Completed Upload to Cloud...");
}
catch (CustomExceptionNoMessage ce)
{
MessageBox.Show(ce.Message);
}
catch (System.IO.IOException e) //CHANGED THIS LINE, AND I AM UP AND RUNNING (Changed to Exception e)
{
MessageBox.Show(e.Message);
}
return true;
}
public class CustomExceptionNoMessage : Exception
{
public CustomExceptionNoMessage()
{
}
public CustomExceptionNoMessage(string message)
: base(message)
{
}
public CustomExceptionNoMessage(string message, Exception inner)
: base(message, inner)
{
}
}
private void button1_Click(object sender, EventArgs e)
{
LoadFile();
}
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;
}
}
How to catch all exceptions in try catch block in Xamarin.Android
I am very frustrated on how Xamarin.Android handles unhandled exception which is very weird, I added three exceptions for all api queries respectively:
try
{
// api query using `refit`
// json parsing using `newtonsoft`
}
catch(System.OperationCanceledException e)
{
// user cancelled the query, show option to retry
}
catch(ApiException apiException)
{
// theres an api exception , show error message to users , show option to retry
}
catch(Exception e)
{
// unknown exception ignore , show error message to users , show option to retry
}
This try catch blocks works most of the time, but there is one certain scenario when our server is down, and it just throws exception and crashes the app over and over again until the server is back up.
This is the exception that keeps on bugging us :
Xamarin caused by: android.runtime.JavaProxyThrowable: Newtonsoft.Json.JsonReaderException
As you can see in JsonReaderException hierarchy, it inherited System.Exception which is the last catch block i used.
and I checked this JsonReaderException it extends from Exception , In which our try catch block should handle it.
Now im wondering is there any way that we can catch all those pesky unhandled exceptions?
I'm getting unhandled exceptions in this way
public void Init()
{
AndroidEnvironment.UnhandledExceptionRaiser += OnAndroidEnvironmentUnhandledExceptionRaiser;
AppDomain.CurrentDomain.UnhandledException += OnCurrentDomainUnhandledException;
TaskScheduler.UnobservedTaskException += OnTaskSchedulerUnobservedTaskException;
var currentHandler = Java.Lang.Thread.DefaultUncaughtExceptionHandler;
var exceptionHandler = currentHandler as UncaughtExceptionHandler;
if (exceptionHandler != null)
{
exceptionHandler.SetHandler(HandleUncaughtException);
}
else
{
Java.Lang.Thread.DefaultUncaughtExceptionHandler = new UncaughtExceptionHandler(currentHandler, HandleUncaughtException);
}
}
private void OnAndroidEnvironmentUnhandledExceptionRaiser(object sender, RaiseThrowableEventArgs e)
{
AndroidEnvironment.UnhandledExceptionRaiser -= OnAndroidEnvironmentUnhandledExceptionRaiser;
_logger.LogFatal($"AndroidEnvironment.UnhandledExceptionRaiser.", e.Exception);
e.Handled = true;
}
private void OnCurrentDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
AppDomain.CurrentDomain.UnhandledException -= OnCurrentDomainUnhandledException;
var ex = e.ExceptionObject as Exception;
if (ex != null)
{
_logger.LogFatal("AppDomain.CurrentDomain.UnhandledException.", ex);
}
else
{
_logger.LogFatal($"AppDomain.CurrentDomain.UnhandledException. ---> {e.ExceptionObject}");
}
}
private void OnTaskSchedulerUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
{
_logger.LogFatal("TaskScheduler.UnobservedTaskException.", e.Exception);
}
private bool HandleUncaughtException(Java.Lang.Throwable ex)
{
_logger.LogFatal("Thread.DefaultUncaughtExceptionHandler.", ex);
return true;
}
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;
};
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);
}
}