Silverlight 3 XamlReader Exception not caught - silverlight

when I use XamlReader.Load() with an invalid XAML string, the resulting XAMLParseException is not caught although beeing in a try-catch-block:
try
{
UIElement xamlCode = XamlReader.Load(XamlText) as UIElement;
}
catch (Exception ex)
{
ErrorText = ex.Message;
}
The code is called from the Tick-Event of a DispatcherTimer, but also in Events like MouseLeftButtonDown the exception is not caught resulting in a break in the Line where I call .Load().
Does anyone know how to catch this Exception and resume normal programm activity?
Thanks, Andrej

It is completely unfathomable that this code would not catch the exception. How do you determine that the XAMLParseException is occuring here? Are you sure is not coming from some other Xaml Load in the project?

Is this always the case ? or onlys while debugging ?
I'm aware this is an extremely late answer and you might have found the solution to it, for as reference to people finding your question similar to theirse (like my case ), my answer might still be of use.
If its happening while debuggin, it might be because the exeption is configured to be thrown.
You can change this:
Customize the Debug menu, adding the "Exceptions" command to it.
In the Exceptions configuration, Drill down to System.Windows.Markup.XamlParseException, which is under Common Language Runtime Exceptions.
Remove the check from the "Throw" column.

There are various Silverlight operations that get "re-marshalled" onto separate threads for what are presumably various good and sufficient reasons. It looks kind of like this:
Dispatcher.BeginInvoke(() => LoadSomeXamlOrSomething());
Any exception thrown within LoadSomeXamlOrSomething() won't be caught by normal try/catch blocks. This happens even in SL 4 with things like loading images with invalid formats. It's annoying, and MS needs to come up with a better way to handle this, for instance, by letting you register an exception handler when you make the call.
Until MS figures this out, your options are:
Fix the underlying XAML error.
Catch the exception in App.Application_UnhandledException.

Related

Uipath try/catch problem - throwing system exception

Having some trouble with try/catch in UiPath:
Got two different projects with their own workflows, with try catch implementations exactly the same in both.
However, one of the try/catch is working absolutely fine, whereas the other one is giving troubles with the following error when I Throw an exception, and then the steps defined in the catch block doesn't even trap it and execute.
Thoughts/Suggestions will be much appreciated - Thanks!
RemoteException wrapping System.Exception: <My user defined message>
at System.Activities.Statements.Throw.Execute(CodeActivityContext context)
at System.Activities.CodeActivity.InternalExecute(ActivityInstance instance, ActivityExecutor executor, BookmarkManager bookmarkManager)
at System.Activities.ActivityInstance.Execute(ActivityExecutor executor, BookmarkManager bookmarkManager)
at System.Activities.Runtime.ActivityExecutor.ExecuteActivityWorkItem.ExecuteBody(ActivityExecutor executor, BookmarkManager bookmarkManager, Location resultLocation)
If you have been using the Try Catch with the general Exception, it should be working in the same way in any project.
I believe you was a bit confused by the running mode.
So I assume in one project you fired the project in the debug mode. This stops on the exception when it occurs. If happening you need to hit the continue button.
But if you run the project with the Run button, it will ignore the exception handling as breakpoint and will continue now without any break.
So make sure in a live test you always run it with the run button and not with the usual debug button.

WPF exits in InitializeComponent(), no error, can't debug

I have an app that used to work well, I did some modifications and such. Now, only about 1/2 the time it runs. I installed the app to a laptop and it doesn't run at all.
There are no errors, warnings, or ui shown by the task bar shows the app momentarily.
Even when I run inside visual studio and put a break point on InitalizeComponent(), I can't seem to locate anything causing the problem.
My code essentially looks like this:
Application.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException;
this.Dispatcher.UnhandledException += Dispatcher_UnhandledException;
try
{
InitializeComponent();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
log("Initalizing....");
This is wpf 4 in vs2015. Any ideas how to get some type of error message before it exits and figure out what is causing the problem? The app works fine once it actually runs. The event viewer on the laptop shows some messages, something about faulting in KernalBase.... nothing useful.
I'm not sure if InitalizeComponent() is the issue, but when I put a BP on it and step through the code, it always exits at that point.
As #Breeze mentioned, you need to strengthen the exceptions, like that:
Go to Debug -> Exceptions... OR Ctrl+Alt+E and you'll see this window:
Mark this two:
Common Language Runtime Exceptions and
Manage Debbugging Assistants.
REMEMBER after finish using them unmark them because it also throws exceptions you don't need to deal with a lot of times.

Why to use multiple catch blocks?

We can use multiple catch block in Try-Catch.
But my Question is : why to use multiple catch blocks when it can be done by using single catch block?
Suppose I want exact cause of my problem, I can get that by Ex.message
If I want to show customized message to user, I can show it by putting If-Else loop on Ex.Message.
Thanks in advance.
To handle the individual exception accordingly.
For example:
If your program is handling both database and files. If an SQLException occurs, you have to handle it database manner like closing the dbConnection/reader etc., whereas if a File handling exception then you may handle it differently like file closing, fileNotFound etc.
That is the main reason in my point of view.
For point numbers 1 and 2:
If showing error message is you main idea then you can use if..else. In case if you want to handle the exception then check the above point of my answer. The reason why I stretch the word handling is because it is entirely different from showing a simple error message.
To add some quotes I prefer Best Practices for Handling Exceptions which says
A well-designed set of error handling code blocks can make a program
more robust and less prone to crashing because the application handles
such errors.
This works only if all exceptions share the same base class, then you could do it this way.
But if you do need exception type specific handling, then I would prefer multiple try-catch blocks instead of one with type-depending if-else ...
You can also ask why do we need the Switch - Case. You can do it with If - Else.
And why do you need Else at all. You can do it with If (If not the first condition, and...).
It's a matter of writing a clean and readable code.
By using single catch clock you can catch Exception type - this practice is strongly discouraged by Microsoft programming guidelines. FxCop has the rule DoNotCatchGeneralExceptionTypes which is treated as CriticalError:
Catching general exception types can hide run-time problems from the library user, and can complicate debugging.
http://code.praqma.net/docs/fxcop/Rules/Design/DoNotCatchGeneralExceptionTypes.html
The program should catch only expected exception types (one ore more), leaving unexpected types unhandled. To do this, we need possibility to have multiple catch blocks. See also:
Why does FxCop warn against catch(Exception)?
http://blogs.msdn.com/b/codeanalysis/archive/2006/06/14/631923.aspx

How to Debug XAML Parsing Errors in Silverlight?

I run into the following issue semi-regularly: I make changes to XAML or some resources used by it and when I go to load up the Silverlight project in debug mode it only gets as far as the spinning Silverlight-loading animation.
I've tried attaching the VS08 debugger to the process but it doesn't do anything at this point (works fine once I'm in the Silverlight but not before.)
From previous experience I've noticed this happens when there're problems with the XAML or the resources in it but my only solution so far has been to dissect the code line-by-line until I spot the problem.
Is there an easy way to debug/diagnose these situations?
UPDATE
I found this question with some help, but it still doesn't provide a good way to debug these types of issues.
This has been a real pain to debug but I finally found the problem hidden deep in the constructor to one of our custom controls (which was looking for a resource that wasn't there.) The real problem isn't fixing the issue but finding it.
I found that IE responds to exceptions in passed from Silverlight to the DOM but you don't get that same sort of feedback in the Chrome browser (which I use.) A solution that actually helps a great deal (even moreso than the IE tip) is to modify the ReportErrorToDOM() method in App.xaml.cs to the following:
private void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e)
{
string errorMsg = String.Empty;
try
{
errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace;
errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", #"\n");
System.Windows.Browser.HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight Application " + errorMsg + "\");");
}
catch (Exception)
{
#if DEBUG
MessageBox.Show(errorMsg);
#endif
}
}
This gives you the position in the XAML where the issue is starting. It's not an ideal debugger, but it does help.
This is not the ultimate answer but can often help
In Visual Studio :
Click Debug > Exceptions
Click 'Find' and search for XAML
Click the 'Thrown' button next to System.Windows.Markup.XamlParseException
Start your project in debug mode. Any Xaml exceptions will be shown immediately. Check the inner exception sometimes for further information.
I wasted soooo much time before I finally figured this one out!
This may not apply, but one frequent source of XAML errors is due to uncaught exceptions within converters that you're using as resources. People often forget to use a try-catch block in their converters, and when something blows up in there you end up having to dissect your code line by line.
And, take this with a grain of salt, but depending upon the situation, you may be able to copy-and-paste some of your XAML into a WPF project and get better error messages. I've never relied on this tactic myself, but I recently heard about it from an experienced WPF/SL developer who's far smarter than me, so it might be worth a shot. :-)
Per microsoft: The end user at this time cannot debug the XAML Parser, only MS can do this. The new version of Silverlight 4 XAML Parser has been completely re-written using managed code and hopfully they will give us a better way to debug it. I know this as I just had an issue and opened a support case and was informed this by a Silverlight Dev.
The clkosest I could ever come to seeing what was going on with the parser was using Silverlight Spy:
http://firstfloorsoftware.com/silverlightspy/download-silverlight-spy/
Great tool.

Exceptions inside repositories: how do you handle them?

An easy one that I am interested in getting your thoughts on:
With your repository implementations, do you like to let exceptions be thrown inside the repository and leave the exception handling to the caller, or do you prefer to catch exceptions inside your repository, store the exception and return false/null?
It Depends.
Do I let exceptions bubble up? Absolutely. But I want this for connection failure, command failures. Whatever you do, don't just hide these, you need to know about them. I prefer my applications to fail as quickly as possible to reduce side-effects and further damage.
I also log exceptions. I use Log4net to help with this. But I like to log exceptions at the source. I will let them bubble up from there.
Return null? If something cannot be found (i.e. looking for something by id and it isn't there), then I return null, not an exception. But there are cases where I could see throwing a new exception when this happens.
Main point: exceptions should be 'exceptional', not the rule. If an exception is thrown, it should be because something is really wrong and you need to fix it.
I usually let exceptions leak, though if I'm in a particularly Enterprisey mood I'll wrap them in a RepositoryException to keep clients from caring about the underlying storage engine.
I would never return false/null instead of an exception, as there's already a meaning behind those values.
In rare cases, you could have a brain-dead storage engine that generates exceptions on non-exceptional cases - and I would catch those specific ones and return null if appropriate (eg., if a row does not exist, but the storage engine throws an error on that case - I'd catch it and return null).

Resources