I am trying to code an app for windows phone 8. I want to print the exception to the screen if I get any. So here is what I am doing:
try
{
//The code which I want to handle for exception
}
catch (Exception e)
{
ErrorStatus.Text = e.Message + "\n\n" + e.Source + "\n\n" + e.StackTrace;
}
where ErrorStatus is my TextBlock.
However, the only line in my catch block is giving me an exception during the runtime. The exception is:
A first chance exception of type 'System.UnauthorizedAccessException' occurred in System.Windows.ni.dll
An exception of type 'System.UnauthorizedAccessException' occurred in System.Windows.ni.dll and wasn't handled before a managed/native boundary
Am I doing something wrong syntactically? I am new to C# programming as well as Windows Phone programming.
Edit:
More details of the exception:
System.UnauthorizedAccessException was unhandled by user code
HResult=-2147024891
Message=Invalid cross-thread access.
Source=System.Windows
InnerException:
You need to show your message from the UI thread: web calls always callback on a background worker thread. So, you need to call the Dispatcher to get this to run on the UI thread.
Also you can just use Exception.ToString() to show the message content as a string. This has the advantage of also showing any nested exceptions inside the one you're handling.
As a temporary measure try:
catch (Exception e)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
ErrorStatus.Text = e.ToString();
}
}
More permanently you should either fix the issue or log it to a file so you aren't catching exceptions which are masking bugs in your code.
This is the best way to print out your exception message so that you may know where the problem is:
try{}
catch(Exception ex)
{
await new MessageDialog("Error message:\n\n" + ex.message).ShowAsync();
}
Related
I've developed an application used by a third-party company.
Since I'm a horrible coder the application does still have some bugs which causes it to crash (unhandled nullpointerexception for example).
It's a Windows-forms application running on .NET 4.5 and now they are just getting the classic "An unhandled exception caused the app to terminate, press details for more info".
Trying to convince them that pressing "Details" and sending the stack-trace to me is really useful but they all seem reluctant.
Would it be possible to automate this behaviour, like show them a custom global "Exception catcher" where they can just press a button to send it to me by E-mail.
Inbefore "Global exception handling is bad" and "Why does your application throw nullpointerexceptions, you are a bad coder etc."
BR Tomas Anyuru
I guess the exceptions you get are unhandled.
Because of this, you will have to use the Application.ThreadException event to handle them. Because there is no .NET automatic mail sending and message display, you will have to implement your own inside this event.
Please have a look of an answer I wrote to have some examples of Exception catching strategies.
wrap your whole main() function in try-catch statement.
this way any un-handled exception will roll back and will be catched in your catch block:
static void main()
{
try
{
// the application code...
}
catch (Exception ex)
{
DialogResult result = MessageBox.Show(
"Some error occured, please click ok to send it to the develpoer");
if (result = OK)
email(ex); // this is your function to send the email.
// useful information is also in ex.message
// here program will exit without error!
}
}
you can use log 4 net it is open source logging tools, use a lot by Java developer, and this version is specially for .Net http://logging.apache.org/log4net/
In addition to #Shamim code, you can wrap your main function in try, catch block, since the catch block here will track down the exception occurred inside any function called in the try block.
Shooting a mail inside catch block sometime throws and exception about Thread abort, so finally would be the right place to do so :
catch (Exception err)
{
mailBody = "Error: " + Convert.ToString(err.Message) + "<br /> Source: " + Convert.ToString(err.Source);
//Can display some message to user in an Literal Control from here.
}
finally
{
if (!string.IsNullOrEmpty(mailBody))
{
mailObject.To.Add(mailTo);
mailObject.CC.Add(mailCc);
mailObject.Body = mailBody;
MailService(mailObject);
}
}
MailService is a method to send mail which accept a MailObject as parameter.
I was hoping somebody could enlighten me a little bit on an issue I am facing in regards to async/await exception handling with HttpClient. I have written some code to illustrate, and it is being excecuted on both a Windows Phone 8 device and the emulator:
private async void SearchButton_Click(object sender, EventArgs e)
{
try
{
HttpClient client = new HttpClient();
System.Diagnostics.Debug.WriteLine("BEGIN FAULTY REQUEST:");
string response = await client.GetStringAsync("http://www.ajshdgasjhdgajdhgasjhdgasjdhgasjdhgas.tk/");
System.Diagnostics.Debug.WriteLine("SUCCESS:");
System.Diagnostics.Debug.WriteLine(response);
}
catch (Exception exception)
{
System.Diagnostics.Debug.WriteLine("CAUGHT EXCEPTION:");
System.Diagnostics.Debug.WriteLine(exception);
}
}
Tapping the button that invokes this function, produces the following output in the debugger console, the most interesting being the ones in bold:
BEGIN FAULTY REQUEST:
An exception of type 'System.Net.WebException' occurred in System.Windows.ni.dll and wasn't handled before a managed/native boundary
An exception of type 'System.Net.WebException' occurred in System.Windows.ni.dll and wasn't handled before a managed/native boundary
A first chance exception of type 'System.Net.Http.HttpRequestException' occurred in mscorlib.ni.dll
An exception of type 'System.Net.Http.HttpRequestException' occurred in mscorlib.ni.dll and wasn't handled before a managed/native boundary
CAUGHT EXCEPTION:
(and here it prints out the HttpRequestException)
Of course I am expecting an error in this case since the URL I am calling is nonsense. What I am not understanding here, is why the debugger reports that the exceptions are not handled, when the output simultaneously reports that the exception is caught. Also, the UI side of the app becomes much less responsive while the output is being printed, indicating that something is probably amiss.
Is this not the way to handle exceptions when working with async and await? I appreciate any input! Thanks.
As you are using HttpClient, try to use response.EnsureSuccessStatusCode();
Now HttpClient will throw exception when response status is not a success code.
try
{
HttpResponseMessage response = await client.GetAsync("http://www.ajshdgasjhdgajdhgasjhdgasjdhgasjdhgas.tk/");
response.EnsureSuccessStatusCode(); // Throw if not a success code.
// ...
}
catch (HttpRequestException e)
{
// Handle exception.
}
ORIGINAL SOURCE OF THE CODE: http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client
This is an artifact of the debugger. It's determining that an exception is "uncaught" because it's not caught yet. In this case this is expected behavior.
You are handling the exceptions correctly.
The debugger is telling you that this exception is first chance. When a debugger is attached to your process it gets notified for every exception that is thrown and then based on how the debugger has been configured it will decide what to do with it. You can go through What is first chance exception? for more details.
On a side note, catch specific exceptions only so that you understand which exceptions you are expecting and why.
I'm currently developping an application for WP7 that needs to make calls to a WCF Service Application. I tested the service with a small WPF application and everything went just fine. But now that I call it from my WP7 app, I systematically get the following exception :
An exception of type 'System.ServiceModel.CommunicationException' occurred in
System.ServiceModel.ni.dll but was not handled in user code
System.ServiceModel.CommunicationException was unhandled by user code
HResult=-2146233087
Message=The remote server returned an error: NotFound.
Source=System.ServiceModel
InnerException: System.Net.WebException
HResult=-2146233079
Message=The remote server returned an error: NotFound.
Source=System.Windows
InnerException: System.Net.WebException
HResult=-2146233079
Message=The remote server returned an error: NotFound.
Source=System.Windows
InnerException:
The exception keeps getting lifted despite the fact I make my service call within a try/catch block like this (in MyProjectPath.Model.User.cs) :
public Task<User> Load(string logon, string pwHash)
{
TaskCompletionSource<User> tcs = new TaskCompletionSource<User>();
client.GetUserByCredsCompleted += ((s, e) =>
{
if (e.Error == null) tcs.TrySetResult(e.Result);
else
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("Error encountered while getting data :");
sb.AppendLine(e.Error.Message);
MessageBox.Show(sb.ToString());
}
});
try
{
client.GetUserByCredsAsync(logon, pwHash);
}
catch (System.ServiceModel.CommunicationException ex)
{
MessageBox.Show(ex.Message);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return tcs.Task;
}
And when executed, the exception occurs here (in System.ServiceModel.ni.dll) :
public MyProjectPath.ServiceReference.User EndGetUserByCreds(System.IAsyncResult result) {
object[] _args = new object[0];
// Exception gets lifted by the following line :
MyProjectPath.ServiceReference.User _result = ((MyProjectPath.ServiceReference.User)(base.EndInvoke("GetUserByCreds", _args, result)));
return _result;
}
Did anyone already encountered this problem and solved it ? I must admit I'm pretty clueless here...
You're calling an asynchronous API. Although you're wrapping that call in a try/catch block, that call will presumably be starting up a new thread or queueing a request for another existing thread to pick up. Either way, your try/catch is only protecting you against exceptions thrown on the thread which makes the call, and there aren't any. The (start of) your asynchronous call succeeds just fine, so the catch block never comes into effect, and then control is passed to the other thread and this is where the exception is thrown.
You can't protect against exceptions in EndGetUserByCreds by wrapping your call to GetUserByCredsAsync in a try/catch. The two methods are executing at different times different threads. You need to modify EndGetUserByCreds so that it catches exceptions and deals with them appropriately, rather than letting them crash the thread.
Exceptions are used throughout the component I'm working in for API error handling:
catch (Exception ex)
{
// ex.ToString() below may be something like "database is locked"
string error = string.Format(
"Error when trying to create a playlist: {0}", ex.ToString());
throw new Exception(error);
}
Basically a lower-level component will throw an Exception with detailed specifics of the error, and this will be caught at a higher-level with a more generic, user-friendly error message.
When my client application processes this application, it calls ex.ToString() to get the complete error string, but this also includes the call stack.
Error: exceptions.RuntimeError: Error when trying to create a playlist:
System.Exception: database is locked
at <very large call stack here>
Is there an easy way to prevent the last section (i.e. at <very large call stack here>) from appearing in the error message, without having the parse the string? This is being returned to the user and I want the error to be user-focused not application-focused.
Try using Exception.Message instead of Exception.ToString:
string message = string.Format(
"Error when trying to create a playlist: {0}", ex.Message);
throw new YourException(message, ex);
I'm handling all of my unhanded exception in the code but whenever one happens (not during debugging) I get my error window and as soon as it closes "Unhandled application exception has occurred in your application" window pops up. How do I suppress it?
PS : I am not using ASP.NET , I'm using Windows Forms
You cannot suppress AppDomain.UnhandledException. Something really nasty happened, a thread in your program died from a heart attack. The odds that the program will continue to run in a meaningful way are zero, .NET puts an end to the misery by terminating the program.
Write an event handler for the AppDomain.CurrentDomain.UnhandledException event and log or display the value of e.ExceptionObject.ToString() so you know what caused the mishap. That gives you a hint how to fix your code. If any, it may well be something that you cannot fix yourself. Some kind of database server malfunction for example. Doing anything to intentionally hide the error is therefore a Very Bad Idea. Your customer's support staff will have no idea what to do.
For Windows Forms, you can send unhandled exceptions (that would otherwise cause the unhandled exception window to pop up) to your exception handler by adding the following in the Main() method, before the Application.Run() method is called:
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
You can subscribe your handler to the unhandled exception event by adding the following to the form's constructor or elsewhere:
Application.ThreadException += myHandler;
And your form's handler method would look like this:
void myHandler(object sender, System.Threading.ThreadExceptionEventArgs e)
{
//do something
}
You can find more information about this on the msdn.
Here's a solution to show all unhandled exceptions, both managed and unmanaged types:
static void Main() {
try {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
Application.ThreadException +=
new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
Application.Run(new Form1());
}
catch (Exception ex) {
MessageBox.Show("A fatal error has occurred. Please contact your admin\n" +
"Exception type: " + ex.GetType() + "\n" +
"Exception Message: " + ex.Message + "\n" +
ex.StackTrace, "Fatal Exception");
if (ex.InnerException != null) {
MessageBox.Show("Inner Exception:\n" +
"Exception type: " + ex.InnerException.GetType() + "\n" +
"Exception Message: " + ex.InnerException.Message + "\n" +
ex.StackTrace, "Fatal Exception (inner)");
}
}
}
static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e) {
throw new Exception(e.Exception.Message, e.Exception);
}
To test this, I used C++/CLI to throw an unmanaged exception. These won't get caught properly unless the above Application_ThreadException Handler is present.
I would use exception shielding.
Windows App Example
This one shows use for Services
Exception Shielding
Its part of the enteprise library, and allows you to filter out exceptions as well as remap them, to hide the details.