Error in CanExecute() - how to get rid of dialog? - c#

I'm trying to handle exceptions in a dialog so that if any exception occurs, the dialog will be closed and the application will not crash. As you can see, I use a simple try-catch block:
IDialogView dialog = null;
try
{
if (_dialogViewModel == null)
{
dialog = ViewFactory.SomeDialog();
_dialogViewModel = new DialogViewModel(dialog);
_dialogViewModel.LoadData();
}
_dialogViewModel.ShowDialog();
}
catch (Exception ex)
{
if (dialog != null)
dialog.Close();
_dialogViewModel = null;
MessageBox.Show("Sorry, there was an error in the dialog.", "Error",
MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
The problem happens when an error occurs in button's CanExecute() event handler. Error is successfully caught, but when I show the MessageBox to the user, CanExecute() executes again, and so the error happens again. In the end it results in application crash.
I've googled some info, and it were said to make sure that there is no exceptions in CanExecute() event handler. But something like this can happen somewhere else, and that's why I want to simply catch ALL exceptions in the dialog entry point without working with every method.
So, my question is: how to destroy the dialog so that after exception catch it won't show again anymore? Close() didn't work, because before closing it still calls CanExecute().

As you found when you googled, you should make sure that a CanExecute handler is a) lightweight and b) never throws an exception. You are running into the main reason for this: a CanExecute will be run repeatedly, and automatically, by the framework. It will run when focus changes, on input events, when databindings change, and in response to a number of other reasons that you have little to no control over.
The problem is: you do have an error, and that error is occurring repeatedly. That means you can choose between crashing, or showing the dialog repeatedly. Or, you can do something about the error.
Your answer: fix the error.
(Your handler as it stands is fine for your other errors. Leave it there. But this particular error, you need to fix right away.)

Related

Stop startActivity(intent) when going in catch block from another class

I am developing an Android Xamarin appliation in which I have an activity with a button. Some of the code in the button is this:
fsp_SellDet_New_ByItemID fsp_SellDet_New_ByItemID = new fsp_SellDet_New_ByItemID(this);
fsp_SellDet_New_ByItemID.ExecuteNonQuery(_SellID,
_ItemID,
_PodID,
_ItemSellQty,
_ItemPrice,
_ItemPricePer,
-_BaseDiscount,
-_AdditionalDiscount,
_ItemSum,
_ItemVAT,
_ItemCode,
_ItemShortName,
_ItemBrand,
_ItemIssue);
Intent i = new Intent(this, typeof(SellDet));
StartActivity(i);
Finish();
My problem is that inside the ExecuteNonQuery method I have handled exceptions in a try and a catch block like so:
catch (Exception ex)
{
_dlgAlert = new AlertDialog.Builder(this).Create();
_dlgAlert.SetMessage(ex.Message);
_dlgAlert.SetTitle(Resources.GetString(Resource.String.Error));
_dlgAlert.SetButton("OK", delegate { });
_dlgAlert.Show();
return;
}
Even tho I am using "return;", Android still opens the next activity so I cannot really see what the exception was, since by the time the AlertDialog shows up, the next activty is already opened.
Can you give me some advices on how to make it so if I receive an exception in the ExecuteNonQuery method, an AlertDialog will popup and it won't go in the next activty.
Or maybe can you tell me how to make it, so that you will have to press "OK" on the alertDialog and then it will go in the activty. Remember, the AlertDialog is inside the executeNonQuery method in the newly created class, not in the button method..
Thank you in advance
There are many ways to fix this issue. In no particular order (let me know if you need to see coded examples for any of them):
Do not catch the exception in ExecuteNonQuery() and instead catch it within the calling method
Have ExecuteNonQuery() return a bool, false if an exception occurs and true if not. Then put an if check around your StartActivity code
Pass an Action into your ExecuteNonQuery() that would run within the empty delegate you are passing to _dlgAlert.SetButton("OK", delegate { /* Passed in Action executes here */ });, the Action would have your StartActvity code in it

UnauthorizedAccessException can't be caught

I've recently run into this problem, and it doesn't make sense.
the following snippet is real:
try
{
File.Create(targetFile);
//File.WriteAllText(targetFile, $"test {DateTime.Now.ToString()}");
}
catch (UnauthorizedAccessException uaex)
{
}
I have checked it step by step, as soon as i get with the debugger to the "File.Create()" method, the exception rises, and it doesn't enter the catch block, also, if i remove the try-catch, it doesn't bubble up to the calling of the method which contains this.
Anyone got any idea why the try-catch and the bubbling doesn't work?
ps. The location where I am trying to create the file is write protected on purpose, this is just a way to check if it is.
I've made a mistake.
The exception is actually being caught, if you put anything in the catch block, it does execute.
To be fair the debugger confused me, by showing the exception pop-up right at the calling of the method, but that was solved by restarting the IDE

Exit Method without ArgumentException

i have a Cancel button on a Progressbar, which is used to Show the Progress of Uploading e-Mails,
now i want this button to Exit the method which Uploads e-Mails.
My plan, once the button gets pressed, make bool cancelUpload true.
i have been unlucky to exit the method with the use of break or simply through an if Statement.
but now i found online that i could throw an Argument Exception,
which i implemented as follows:
if (cancelUpload)
{
throw new ArgumentException("SomeText");
}
but the Problem i have with this, is that once the User clicks on Cancel, he gets an Exception, which Looks like an Error or something went wrong, is there a way to get out of the method, without it looking as though something went wrong?(similiar to ArgumentException)
Thanks a lot in Advance!
Edit: The Method (void Method) is to big to be shown,
but when i tried to return;, i got an Error in Visual Studio saying:
TargetInvocationException was unhandled Exception has been thrown by the target of invocation

Why does throw crash my program but return doesn't?

I am trying to catch exceptions for my form client not being able to establish a connection to a server with this in the Connect callback:
try
{
client.EndConnect(async);
}
catch (Exception e)
{
client.Close();
return;
}
This works fine but this behavior is encapsulated in to a class so I want to call throw; instead of return; so that the client class can handle it instead, like so:
try
{
client.Connect(host, port);
}
catch
{
Console.WriteLine("Could not connect to: " + host + ":" + port.ToString());
}
So why not just call throw; then? Well, for some reason if I call throw;, throw new Exception();, or basically anything other than return; the program failsfast. I'm really not sure what's causing this. I tried removing client.Close(); to see if it was the problem but nothing. If I don't call return; the program just immediately exits with no error.
Anyone know what's going on here?
Edit: I do not understand why I am getting downvoted so much. I showed how I am attempting to catch these exceptions and am asking why they are not working properly. I think the problem may be (not sure, just came up with this) because within the asynchronous callback, because it is a new thread in the ThreadPool, calling throw; does not do anything because, because it is not synchronous, there is nothing to throw back to and the application dies. Even with this knowledge, I am not sure how to solve this problem unless I put some sort of try-catch on the entire program.
I suppose a solution could be just sticking with return; because there is nothing to throw back to (due to the asynchronous callback nature of the method) and instead raise an event indicating a failure of connection. Regardless, many thanks for the downvotes and helping me solve this problem. Oh wait...
What's happening is that the EndConnect is not happening on the same thread as your BeginConnect. When EndConnect throws an exception, it is caught by the worker thread's unhandled exception handler, which fails fast (the other option is that it gets ignored and you never find out that your code isn't working).
You have to come up with a way to tell your main form thread that the connect failed.
As others have pointed out, you'll need to catch your exception one way or another to avoid program termination.
For some ideas on how you can do that "globally", see How to catch ALL exceptions/crashes in a .NET app. Whether this is actually a good idea depends on the specific needs of your program...
Relevant for WinForms:
Can't tell based on your question alone, but in case this is actually a WinForms application, you may need to be cognizant of the difference in behavior of modal forms that throw exceptions, depending on whether the debugger is active or not. Let's say we have two forms - the second one is shown as a modal child of the first one:
If application was started through debugger, second form is closed and and stack unwinding goes all the way to the first form's catch block (if any).
If application is started outside debugger, stack unwinding stops before second form is closed and generic exception message is displayed. The second form stays open and catch block in the first form is never reached.

Why does this error not get caught?

I have the following code in my project, deleteselector is a form that has a datagridview (with autosize columns) on it.
try
{
if (deleteSelector.ShowDialog() == DialogResult.OK)
{
}
}
catch (InvalidOperationException)
{
//Bug workaround
}
The try catch is because a pop-up form with a gridview on it trows a invalidoperationexception once in a while. This is the suggested workaround, see
http://connect.microsoft.com/VisualStudio/feedback/details/145633/invalidoperationexception-thrown-when-a-form-with-a-bound-datagridview-with-auto-sizing-columns-is-shown
Earlier, I used Show on the deleteSelector, and the workaround worked perfectly. Now, with showdialog it seems that the error is not catched anymore (I get an uncatched error message). Why is the error not catched?
ShowDialog runs the dialog on a separate thread, so the exception is being thrown in a different stack to your exception handler.
I suggest you try to find a different workaround - just catching InvalidOperationException is pretty horrible, and I wouldn't like to bet that the form would be in a sensible state afterwards.

Categories

Resources