I'm currently learning after a book about how to convert xaml code into objects during runtime.
I have the following code:
try
{
ctrl = XamlReader.Load(xaml) as UserControl;
}
catch (Exception exc)
{
OnXamlResult(new XamlCruncherEventArgs(exc.Message)); return;
}
The code is not mine, I took it from the book.
The problem is that try-catch does not work properly, or at least as I know till now.
During debugging the program stops when it reaches the line :
ctrl = XamlReader.Load(xaml) as UserControl;
without catching the exception.
What am I doing wrong or how can I solve this problem?
"xaml" is a string. It is taken from a textbox and if the xaml is correctly typed by the user the program should convert the xaml code into object otherwise it should display the corresponding error.
About how the program reacts, i can say that debug stops(it returns me to visual studio pointing the error) and it is not behaving like going into a infinite cycle.
It's probably the debugger breaking as the exception occurs. Stick a breakpoint inside the catch and F5 to continue, it should carry on and hit your breakpoint.
And by "breaking", I don't mean it fails, I mean it pauses execution of the app on the offending line of the exception, so it's a Good Thing in this instance.
If you are using Visual Studio, you can enable/disable this "break on exception" behaviour:
Debug -> Exceptions... (Ctrl + Alt + E)
Common Language Runtime Exceptions, check the boxes to the right as needed.
As for the exception itself, unless it's there specifically to show exceptions, it is likely having trouble loading the provided XAML string.
Related
I have code in try block which is throwing out of memory exception.. depending on size of input. Problem is that VS is breaking on that line even tough i have it in try/catch block.. so it should be handled.
try
{
Array arrayND = Array.CreateInstance(typeof(ushort), sqs.Select(n => n.Count).ToArray());
}
catch (Exception e)
{
MessageBox.Show("Input is too big. Please limit number of sequences or there length.");
}
Is it possible to set visual studio so it would not break on code in try block when exception is thrown? thanks.
In the menu, goto Debug --> Windows --> Exception Settings.
From the opened window, notice the Common Language Runtime Exceptions category. You can uncheck the whole category, or, if you expand the category, you can uncheck only the exception types you don't want VS to break on.
Little side note: beware about trying to handle OOM exceptions like any other exception. See here for more information: When is it OK to catch an OutOfMemoryException and how to handle it?
Normally I want the debugger to break on ArgumentOutOfRangeException.
But within my try catch(ArgumentOutOfRangeException) that exception is already handled and so I want the debugger to not break.
I tried the DebuggerStepThrough attribute, but it still breaks.
You can do this by setting the debugger to break on user unhandled exceptions.
Go to Debug -> Exceptions, Common Language Runtime Exceptions, de-tick (uncheck) the Thrown box. Of course you can get very precise with what you want to break on by drilling down into that list. Be aware that this setting takes effect across the whole solution, you can't set it per class or method. If you do want to be more selective per method, then consider using compile directives to not include that bit of code during debug time.
As for the DebuggerStepThrough attribute, that is to prevent breaking on break points, nothing to do with breaking on exceptions.
You should check your visual studio isn't set to break on all exceptions
On the Debug menu, click Exceptions.
In the Exceptions dialog box, select Thrown for an entire category of exceptions,
for example, Common Language Runtime Exceptions.
Microsoft Visual Studio Help
There is a way. First disable debugging code that is not yours. Go to Tools > Options > Debugging > General > select "Enable Just My Code (Managed only)". Now tell the debugger that this one function is not part of your code with DebuggerNonUserCodeAttribute:
[System.Diagnostics.DebuggerNonUserCode()]
private void FunctionThatCatchesThrownException()
{
try
{
throw new ArgumentOutOfRangeException();
}
catch (ArgumentOutOfRangeException ex)
{
//...
}
}
If an exception (some other than ArgumentOutOfRangeException) gets out of the function debugger will catch it as usual, but the location of interception will be where the function is called.
I've followed this advice to get debugging working for NUnit tests.
http://www.blackwasp.co.uk/NUnitCSharpExpress.aspx
However, i have several tests that do Assert.Throws<...>, which causes the debugger to break when the exception i'm testing for occurs, when really i want it to break if an exception occurs outside of those calls.
How can i get the debugger to ignore exceptions caused from within these kinds of methods?
EDIT: I've event tried the below, which doesn't work!
[Test]
public void InstanciatingWithNullParameterThrowsException()
{
try
{
Assert.Throws<ArgumentNullException>(() => new CachedStreamingEnumerable<int>(null));
// This still throws and stops be being able to debug tests called after this one
}
catch
{
}
}
Here is what worked for me (although in Visual Studio Professional, not Express, but I guess that should not matter).
Bring up the "Exceptions" Dialog as suggested by Ninjapig.
Click on the Add... Button, to open the "New Exception" dialog.
Select "Common Language Runtime Exceptions" in the drop down box
In the Edit box enter "NUnit.Framework.AssertionException".
Click OK to close the "New Exception" dialog.
Back in the "Exceptions" dialog make sure that both checkboxes (Thrown and User-unhandled) are unchecked.
Now, the debugger should completely ignore a NUnit assertion failure (i.e. a thrown, caught or not, NUnit.Framework.AssertionException).
UPDATE: This will only prevent from breaking into the debugger, it cannot ignore the exception itself; i.e. it will not alter the actual program flow. Appart from changing or replacing or encapsulating the Assert-calls in try-catch blocks, I don't think there is anything that can achieve that (at least not automatically).
I'm uncertain if VS2010 Express has this option, but you can choose the exceptions to break on .
Go to the 'Debug' menu, then select 'Exceptions'
and from here you can select what exceptions to break on
I've ended up referencing nunit-gui-runner.dll and invoking it like
NUnit.Gui.AppEntry.Main(new string[] { Dll });
This brings up the NUnit gui. I can then run the specific test i'm interested in.
I had the same problem. Although your original approach (without the need for a try...catch block) works for most exception types, ArgumentNullException doesn't work. I fixed it like this:
[Test]
public void InstanciatingWithNullParameterThrowsException()
{
bool isArgumentNullExceptionThrown = false;
try
{
new CachedStreamingEnumerable<int>(null);
}
catch (ArgumentNullException)
{
isArgumentNullExceptionThrown = true;
}
Assert.That(isArgumentNullExceptionThrown);
}
It's not as elegant, but it does seem to work.
I'm having trouble with an application I've written, it's basically creating dynamically generated assemblies based on code input by the user.
It compiles and runs fine, but for some reason, sometimes when an Exception occurs in that compiled assembly, it crashes the main program even though everything is thoroughly coated in try/catch blocks.
I add try/catch blocks to surround the user's code in the generated assembly, and also try/catch around the Invocation of the assembly in my app:
StringBuilder verificationErrors = new StringBuilder();
argz[0] = "hello!";
argz[1] = verificationErrors;
object loResult = null;
try
{
loResult = loObject.GetType().InvokeMember("doThis", BindingFlags.InvokeMethod, null, loObject, argz);
}
catch (Exception p)
{
MessageBox.Show(p.Message);
}
It looks like the error is being thrown outside the scope of my app, so it doesn't know how to catch it or something to that effect... any ideas?
It's possible that the invocation of p.Message is throwing an exception. One would presume that we're using the default Message property, but it could be a custom exception that overrides the Message property.
I would wrap the code in the catch block with a further try...catch, and if it throws an error, just say "An unexpected error occurred", and log whatever you can about it.
If you run the program in debug and instruct Visual Studio to break when an exception is thrown, you should be able to inspect the stack trace and determine which method is throwing the exception.
Go to Debug / Exceptions...
Check the box in front of "Common Language Runtime Exceptions", in column "Thrown"
Click "OK"
Run the program in debug mode
There is a place in my WinForms program that throws a MyOwnException.
void CodeThatThrowsMyOwnException()
{
...
throw new MyOwnException("Deep Inside");
...
}
Further up the stack, there is a simple try/catch block
try
{
CodeThatThrowsMyOwnException();
}
catch (MyOwnException moe)
{
MessageBox.Show("Hit this point in the code! Hurray!");
}
MessageBox.Show("Later, alligator.");
On a colleague's computer (running VS 2008 SP1 like me) the dialog box shows up. On my computer, it never catches the exception nor shows the dialog box. When I place a breakpoint deep inside the code (CodeThatThrowsMyOwnException) on the line that throws the Exception, it hits the breakpoint on the line. If I press F5 (Debug > Run) it skips passed my catch block and displays the "Later, alligator" message.
Actually pasting the "void CodeThatThrowsMyOwnException() { throw new MyOwnException("Shallow"); }" code into my code (instead of calling my real code) and literally calling "CodeThatThrowsMyOwnException();" in the try block does however get show the message in the catch block.
As far as I can tell, I am not creating any threads and I have looked for try {} catch {} blocks that catch all exceptions but cannot find any in the involved projects (and if they were in there, why would this catch block still work on my colleague's machine?)
Strangely enough running my code by double clicking the executable gives me an unhandled exception on my machine and the same on my colleague's machine. This is a clue that led me to try the following:
When I place a breakpoint at the throw MyOwnException("Deep Inside") line deep inside my code, the call stack contains a line "[External Code]" between my exception handler and the place where I call 'throw MyOwnException("Deep Inside")'. If I put a try/catch MyOwnException block further away from the throw (but on this side of the [External Code] I can still catch the exception, anywhere I place the try catch block (around relevant parts of the function chain):
try
{
CodeChain(...);
}
catch (DrawException de)
{
MessageBox.Show("Hurray!"); // being executed, but only on the 'throw' side of the [External Code] part of the call stack
}
However, when I step outside (below on the stack) the [External Code], the exception does not fire. This is unexpected:
try
{
treeview.Nodes.Add(treeNode); // triggers the aforementioned chain of code with MyOwnException thrown
}
catch (DrawException de) // no matter what I do, this will not handle my cursed MyOwnException
{
MessageBox.Show("Hurray!"); // not being executed
}
This is the heart of my problem: I can't move my catch up the call stack because I need to run lots of tests (see below).
I have a sort of hypothesis, which is that his debugger is magically lifting the exception across thread boundaries (or across external code, i.e. Windows GUI events) in his debugger, whereas in the other three situations (my debugger (without the 64 bit extensions) and also when either machine runs the EXE from windows explorer the exception) the exception is truly unhandled on that thread.
So how do I catch this exception? Re-engineer my whole system to avoid using treeview.AfterSelect? Clearly I don't understand the limitations of exceptions.
Potential problem?
I have a delegate in there to keep my system modular and reusable. Can exceptions be thrown "through" a delegate, across module boundaries?
What I'm trying to accomplish (Testing Harness) and why I need Exceptions
I'm using this in an automated test harness. I need to fix some really tough logical/algorithmic bugs in a complicated GUI system by replaying action scripts (text files) that find these exceptional circumstances and narrow the problem down. (There is probably no good workaround to this in my program, in terms of rewriting or refactoring the design: I need to catch these Exceptions in this QA phase, fix the bugs (tough algorithmic special cases) before I ship so I don't subject my users to such buggy software. It's not like I'm using exceptions for exotic control flow for for fun (cf. Int32.Parse).)
The treeview_AfterSelect is going to be called most of the time by what you're referring to as [External Code]. These will be the result of the user selecting a node or even when the form is loading and you're adding nodes (which I suspect might be happening on your unhandled exception).
If your AfterSelect handler is going to throw exceptions for some reason, you cannot rely on your calling code to handle those exceptions. Otherwise, any other way that AfterSelect gets called could result in an unhandled exception.