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();
}
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;
}
}
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;
}
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 have a code like this,
using (SPSite site = new SPSite("http://site/"))
{
using (SPWeb web = site.OpenWeb())
{
try
{
SPList list = web.Lists["ListName"]; // 2
SPListItem item = list.Items.Add();
Guid itemId = item.UniqueId;
SPListItem itemUpdate = web.Lists["ListName"].Items[itemId];
itemUpdate["PercentComplete"] = .45; // 45% HERE IS EXCEPTION
itemUpdate.Update();
}
catch (Exception e)
{
Console.WriteLine(e);
Console.ReadLine();
}
}
}
I am getting this exception on line itemUpdate["PercentComplete"]
Value does not fall within the expected range.
What I want is
I want this exception to be ignored as if it returns null then keep it null instead of throwing exception,
I already tried this,
Object letSay = itemUpdate["PercentComplete"];
// thought object can be null but same exception
I don't want to try
try {} and Catch {} either.
You just need to check this field existance:
SPListItem item = list.Items.Add();
if (item.Fields.ContainsField("PercentComplete"))
{
item["PercentComplete"] = .45;
}
item.Update();
Not sure because I don't use Sharepoint,but looking at the docs you need to create the field "PercentComplete" before trying to set a value in it.
SPListItem itemUpdate = web.Lists["ListName"].Items[itemId];
itemUpdate.Fields.CreateNewField("PercentComplete", "PercentComplete");
itemUpdate["PercentComplete"] = .45;
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splistitem.fields.aspx
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spfieldcollection_methods.aspx
Let's hope an expert on SharePoint could give you a better answer.....
As a side note: There is no way to ignore an exception. Exceptions are an 'exceptional' event. Something that you cannot expect, not something that you could prevent to happen with proper coding. Accessing an item that doesn't exist is a bad practice and you could easily avoid it.
If you wish you could setup a global exception handler that handles all the uncaught exception adding code like this to your main method
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
And then prepare the following methods
private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
string msg = "Not recognized error:" + e.Exception.Message;
if (e.Exception.InnerException != null)
{
msg = msg + "\r\nPrevious error:" + e.Exception.InnerException.Message;
}
msg = msg + "\r\nStackTrace:" + e.Exception.StackTrace;
msg = msg + "\r\nDo you wish to continue with the application?";
DialogResult dr = AskAQuestion(msg);
.. add logging here ...
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 = "Not recognized error:" + e.Exception.Message;
if (e.Exception.InnerException != null)
{
msg = msg + "\r\nPrevious error:" + e.Exception.InnerException.Message;
}
msg = msg + "\r\nStackTrace:" + e.Exception.StackTrace;
.. add logging here ...
}
}
According to your comment to Steve's answer:
but i wanted to know how can i ignore exception in c#, above code is just an example sir
You cannot ignore an exception in C# without using a try-catch-block. In your case the code should look like this:
try
{
itemUpdate["PercentComplete"] = .45; // 45% HERE IS EXCEPTION
}
catch
{
}
But this code is neither nice, nor should one simply ignore exceptions in first place!
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();
}
}
}