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!
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();
}
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 am unable to get the reason for this Exception:
private void bwWorker_DoWork(object sender, DoWorkEventArgs e)
{
if (Main.bolDebugMode)
MessageBox.Show("Function DoWork is called");
if (Main.ftpsync(Main.strUsername407, Main.strPassword407, sender as BackgroundWorker) == 0)
e.Result = e.Result + "No error in " + Main.strUsername407;
else
{
if (Main.bolDebugMode)
MessageBox.Show("Errors in " + Main.strUsername407);
e.Cancel = true;
e.Result = e.Result + "Errors in " + Main.strUsername407;
if (Main.bolDebugMode)
MessageBox.Show("Errors marked");
try
{
MessageBox.Show("Next step throws exception");
return;
}
catch (Exception error)
{
if (error.ToString() != null)
MessageBox.Show(error.InnerException.Message);
}
}
}
It throws this exception:An unhandled exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll
Additional information: Exception has been thrown by the target of an invocation.
The target (to my limited understanding) is the backgroundworker's RunWorkerCompleted function:
private void bwWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (Main.bolDebugMode)
MessageBox.Show("DoWork Completed. Break: " + e.Cancelled + " Error: " + e.Error + " Result: " + e.Result);
// First, handle the case where an exception was thrown.
if (e.Error != null)
{
lStatus.Text = e.Error.Message;
}
else if (e.Cancelled)
lStatus.Text = "Cancelled: " + e.Result.ToString();
}
else
{
lStatus.Text = "Done! " + e.Result;
Thread.Sleep(Convert.ToInt16(Main.strGlobalWaitTime));
pbProgress.Value = 0;
lStatus.Text = "";
}
if (Main.bolDebugMode)
MessageBox.Show("Analysis completed");
// Enable the Start button.
btnStart.Enabled = true;
// Disable the Cancel button.
btnCancel.Enabled = false;
}
public class Main
{
#region Variables
// Variables - FTP Settings
// Reading tons of variables from a appconfig file like so:
private static string StrGlobalWaitTime = ConfigurationManager.AppSettings["program_globalWaitTime"];
private static bool BolDeleteRemoteFiles = Convert.ToBoolean(ConfigurationManager.AppSettings["program_deleteremotefiles"]);
// Configuring the variables to receive and write
public static string strGlobalWaitTime
{
get { return StrGlobalWaitTime; }
set { StrGlobalWaitTime = value; }
}
#endregion
#region Main function
public static int ftpsync(string strUsername, string strPassword, BackgroundWorker bwWorker)
{
if (Directory.EnumerateFiles(strWorkDirectory, "*.pdf").Any())
{
bwWorker.ReportProgress(0, "Files left! Upload not complete");
Thread.Sleep(Convert.ToInt16(Main.strGlobalWaitTime));
return 1;
}
However, it doesn't even reach the first debugging message box. Thus it must be happening between the return and the beginning of the function. Is he background worker not handing over directly to the RunWorkerCompleted function? Can anyone tell me what I am missing or doing wrong?
This is my first question. I will try to provide as much information as possible. Google searches for the most obvious queries have been done.
The thing to look for whenever you encounter a TargetInvocationException is the InnerException property, which will have the "real" exception.
From the look of it, it will most likely have something to do with trying to access the GUI from inside the worker's thread. Remember that when using the DoWork handler, the code executes in a different thread from the main UI's. Therefore, calls to GUI components must be either done via Invoke calls or avoided all together.
How is it possible that thrown TimeoutException object is null and it throws
Object reference not set to an instance of an object.
in following line:
writeToLog(e2.ToString());
Check out this code.
WebServiceRef.CallResponse callResponse = null;
try
{
callResponse = webServiceClient.Call(callRequest);
}
catch (TimeoutException e)
{
try
{
WebServiceRef.CallStatusResponse callStatusResponse = webServiceClient.CallStatus(callStatusRequest);
if (callStatusResponse.ResponseCode != 0)
{
throw new Exception("nok: " + callResponse.ResponseCode);
}
}
catch (TimeoutException e2)
{
writeToLog(e2.ToString());
}
}
This is my writeToLog method.
private static void writeToLog(String logMsg)
{
using (System.IO.StreamWriter file = new System.IO.StreamWriter(#"log.txt", true))
{
file.WriteLine(DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss ") + logMsg);
}
}
Stacktrace and message is this:
Object reference not set to an instance of an object.
at ...(...) in c:\...cs:line 82
at ...(...) in c:\...cs:line 193
Line 82 is point at
writeToLog(e2.ToString());
There is no way a null Exception instance can be thrown / caught.
Either something must be wrong with your debug symbols or you're not running the correct program. Try logging some test strings here and there to make sure the correct code is executed:
//...
catch (TimeoutException e2)
{
Debug.WriteLine("If you don't see this in the output window then somehow you are not running this app.");
writeToLog(e2.ToString());
}
//...
Building an App for windows store 8.1, i implement my searchbox, following the tutorial.
But, it works good only searching a substring that "startWith" another.
If i try to use something like "contains" i got a crush, an unhandled exception.
It works at the first, but if i change the query in the searchBox it crush ... often, not allways.
I can't understand the debugger message,because it refers to the app code...
That's my debugger message
Debugger:Debugger Break
A break in the debugger session because a user paused the session.
Time: 13/04/2014 12:34:34
Thread:<No Name>[6220]
and refers to
#if DEBUG && !DISABLE_XAML_GENERATED_BREAK_ON_UNHANDLED_EXCEPTION
UnhandledException += (sender, e) =>
{
if (global::System.Diagnostics.Debugger.IsAttached) global::System.Diagnostics.Debugger.Break();
};
#endif
}
my e object got an Exception : incorrect Parameter, handled : false....
that's my SuggestionRequested function, where there is the problem (i think)
public async void OnSuggest(SearchBox sender, SearchBoxSuggestionsRequestedEventArgs args)
{
var deferral = args.Request.GetDeferral();
TransporterExt tr_search = new TransporterExt();
ObservableCollection<TransporterExt> querySuggestions = new ObservableCollection<TransporterExt>();
var queryText = args.QueryText != null ? args.QueryText.Trim() : null;
if (string.IsNullOrEmpty(queryText)) return;
suggested.Clear();
tr_search.name = queryText;
try
{
var suggestionCollection = args.Request.SearchSuggestionCollection;
querySuggestions = await TransporterService.Search(tr_search);
if (querySuggestions != null && querySuggestions.Count > 0 )
{
int i = 0;
foreach (TransporterExt tr in querySuggestions)
{
string strB = sender.QueryText;
string strA = tr.name;
if(await Utility.Compare(strA,strB))
//using this condition all works fine
//if (tr.name.StartsWith(sender.QueryText, StringComparison.CurrentCultureIgnoreCase))
{
string name = tr.name;
string detail = tr.trId.ToString();
string tag = i.ToString();
string imageAlternate = "imgDesc";
suggestionCollection.AppendResultSuggestion(name, detail, tag, imgRef, imageAlternate);
if(tr!=null)
suggested.Add(tr);
i++;
}
}
}
}
catch (Exception exc)
{
//Ignore any exceptions that occur trying to find search suggestions.
Debug.WriteLine("Exception " + exc.Message);
Debug.WriteLine(exc.StackTrace);
}
deferral.Complete();
}
and the Contains utility
public static async Task<bool>Compare(string A, string B) {
bool contains = Regex.Match(A, B, RegexOptions.IgnoreCase).Success;
Debug.WriteLine("regex ="+contains);
return contains;
}
I got this SearchBox in a UserControl, and that's the code of my UC
public delegate void SuggestionsRequested(SearchBox sender, SearchBoxSuggestionsRequestedEventArgs args);
public event Windows.Foundation.TypedEventHandler<SearchBox, SearchBoxSuggestionsRequestedEventArgs> SearchBoxSuggestionsRequested;
private void SearchBoxSuggestions(SearchBox sender, SearchBoxSuggestionsRequestedEventArgs args)
{
if (SearchBoxSuggestionsRequested != null)
SearchBoxSuggestionsRequested(sender, args);
else
Debug.WriteLine("TruckFormUCException");
}
It's possible to search with another logic instead of "startswith"?... where's my fault?