How to disable breaking on exceptions in try/chatch block - c#

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?

Related

Exception Handling error when saving to database

Iam a newbie who needs help. When saving to a database, i get the following error:
A first chance exception of type 'System.Data.SqlServerCe.SqlCeException' occurred in (name of my application)
Please help me with steps to solve this one. Thank you in advance.
First chances exceptions will be shown if you have your Visual Studio settings set so that every CLR exceptions gets reported. This will include exceptions you actually handle.
In Visual Studio's menu, go to Debug > Exceptions and uncheck the Thrown option for Common Language Runtime Exceptions.
Of course that won't make the actual exception go away but you'll be allowed to handle it as you want:
try
{
// do your query
// commit current transaction if possible/necessary
}
catch (SqlCeException ex)
{
// handle exception here and rollback current transaction if possible/necessary
}
finally
{
// ensure proper disposal of any commands and connections you have
}
It goes without saying that you must ensure your query is properly written and that the server objects it tries to work with exists. You generally won't want to handle cases where a comma is missing or a field is not found, for instance. Exception handling must be for exceptional situations your code cannot control, like a faulted connection, a server malfunction, etc.
First of all you might want to check whehter your SQL query is syntactically correct.
Secondly you might want to read about how to handle exceptions in MSDN http://msdn.microsoft.com/en-us/library/0yd65esw.aspx with try-catch statement.
A small example looks like this.
try
{
// ... code which throws exception
}
catch (SqlCeException e)
{
// ... exception handling, e.g. logging, rolling back data,
// telling the user something went wrong, you name it
}
Last but not least you might want to debug your application step by step to see what is causing the error and what the actual SQL Query is throwing the exception.

How to prevent break on specific exception if it's handled

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.

C# rethrow an exception: how to get the exception stack in the IDE?

There has been discussion here before about the correct way to rethrow an exception. This question, instead, is about how to get useful behavior from Visual Studio when using rethrow.
Consider this code:
static void foo() {
throw new Exception("boo!");
}
static void Main(string[] args) {
try {
foo();
} catch (Exception x) {
// do some stuff
throw;
}
}
The exception that comes out has the correct stack trace, showing foo() as the source of the exception. However, the GUI Call Stack window only shows Main, whereas I was expecting it to show the exception's call stack, all the way to foo.
When there is no rethrow, I can use the GUI to very quickly navigate the call stack to see what call caused the exception and how we got there.
With the rethrow I'd like to be able to do the same thing. Instead, the call stack that the GUI shows is of no use to me. I have to copy the exception details to the clipboard, paste it to Notepad, and then manually navigate to whichever function of the call stack I'm interested in.
By the way, I get the same behavior if I add [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] or if I change the catch to just catch (Exception).
My question is: given that the code I have uses rethrow, can someone suggest a convenient way to navigate the call stack associated with the exception? I'm using Visual Studio 2010.
The debugger breaks at the throw in Main because that exception is unhandled. By default, the debugger will only break on unhandled exceptions. Once you've stopped at Main, the call stack for the original exception from foo is present in the exception, but all of the other context has been lost (e.g. locals, stack/memory state).
It sounds like you want the debugger to break on the throw in foo, so you should tell the debugger to break on first-chance exceptions:
Debug ยป Exceptions... (Ctrl+Alt+E)
Check "Thrown" for the exception types you care about (in this case, Commange Language Runtime Exceptions)
Click OK
Start debugging
In this case, the debugger will break immediately when foo throws an exception. Now, you can examine the stack, locals, etc., in the context of the original exception. If you continue execution (F5), the debugger will break again on the rethrow in Main.
Taking another approach, if you're running VS2010 Ultimate, you can also use IntelliTrace to "debug backwards" to see parameters, threads, and variables at the time of the exception. See this MSDN article for details. (Full disclosure: I work on a team closely related to IntelliTrace).
If you use ReSharper, you can copy exception stacktrace to clipboard, then choose in the menu: ReSharper > Tools > Browse Stack Trace (Ctrl+E,T). It will show stacktrace with clickable locations, so you'll be able to quickly navigate.
(source: jetbrains.com)
This feature is also very useful while digging through logs from users (if stacktraces of exceptions are logged).
Not that you should re-throw but here's a blog post about how to preserve the stack trace, essentially it boils down to this:
private static void PreserveStackTrace(Exception exception)
{
MethodInfo preserveStackTrace = typeof(Exception).GetMethod("InternalPreserveStackTrace",
BindingFlags.Instance | BindingFlags.NonPublic);
preserveStackTrace.Invoke(exception, null);
}
...
catch (Exception ex)
{
// do something
// ...
PreserveStackTrace(ex);
throw;
}
Mike Stall has given a great and simple solution to your problem:
Mark the methods where you rethrow the exception with the attribute [DebuggerNonUserCode]
The IDE will consider this is not your code and will not break the debugger in such place, and instead will look further in the stack, showing the next rethrow or the initial exception place.
(if the next rethrow is also annoying, mark it as [DebuggerNonUserCode] as well, etc...)

Catching an Exception across treeview.Nodes.Add / treeview_AfterSelect event boundary

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.

How to log exceptions in Windows Forms Application

I read a lot about how bad catching base Exceptions is and I have to confess that I did it also:
try{
...
}
catch (Exception exception){
MessageBox.Show(exception.Message, "Error!");
MyLogger.Log(exception.Message);
}
Now I would like to do it right and have some questions about it:
Which exceptions should I catch (for example FileNotExists for file manipulation, but what for TableAdapter or ReportClass (CrystalReports))
Where can I see a list of exceptions, that an objects can throw (for example TableAdapter)
Where in Windows Forms Application can I set a static method, which will log any exception to a file for example
Any other suggestions?
Catch whichever exceptions you can reasonably handle. For example, if you're trying to open a file for writing, you should expect that maybe the file is marked read-only, so that would throw an exception. But in the same situation you wouldn't try to catch a null argument exception, because that would be due to programmer error.
They should be found in the function reference in MSDN (you'll have to look it up on each one). For user-defined functions, you'll have to go digging, unless there is additional documentation or summary commentary.
3, 4. Consider using a logging library for .NET
I have one thing to add. If you just want to log an exception without affecting program flow you can always do this:
try
{
...
}
catch (Exception exception)
{
MyLogger.Log(exception.Message);
throw;
}
That's up to you to decide which exceptions your application logic can reasonably expect to recover from.
Exceptions are thrown by method invocations, not objects. In Visual Studio, Intellisense explanations will tell you which exceptions are thrown by an object (provided that the XML documentation describes which exceptions a method throws.
Rather than use a static method, respond to the Application.ThreadException event. The link provided has examples.
MSDN
You can set an event for unhandled exceptions in application events file
(got a VB sample here but i hope you get the point)
Private Sub MyApplication_UnhandledException(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs) Handles Me.UnhandledException
End Sub
You can find the application events in the options of you project.
You should only catch exceptions you can do something about, really.
That's the rule of thumb. I typically have a try/catch around my Program.Main just in case an exception bubbles right to the top and needs logging. You can also handle the CurrentDomain_UnhandledException event, in case exceptions are thrown in other threads than the UI thread (assuming you are multithreading).
In response to "4. Any other suggestions?":
In your example code, a message box is displayed before logging the exception. I would recommend logging the exception before displaying the message, just in case the user sees the error message, panics, and goes on vacation without clicking "OK". It's a minor thing, but message boxes block the program indefinitely and should be used with discretion!

Categories

Resources