I have some strange problem here. Exception thrown by Task always not handled independently how can I try to handle it.
I try this:
http://msdn.microsoft.com/en-us/library/dd997415%28v=vs.110%29.aspx
private class MyCustomException : Exception
{
public MyCustomException(String message) : base(message)
{
}
}
public static void Main()
{
var task1 = Task.Factory.StartNew(() =>
{
throw new MyCustomException("I'm bad, but not too bad!");
});
try
{
task1.Wait();
}
catch (AggregateException ae)
{
// Assume we know what's going on with this particular exception.
// Rethrow anything else. AggregateException.Handle provides
// another way to express this. See later example.
foreach (var e in ae.InnerExceptions)
{
if (e is MyCustomException)
{
Console.WriteLine(e.Message);
}
else
{
throw;
}
}
}
Console.Read();
}
this:
http://dotnetcodr.com/2014/02/11/exception-handling-in-the-net-task-parallel-library-with-c-the-basics/
this:
http://blogs.msdn.com/b/pfxteam/archive/2010/08/06/10046819.aspx
this:
var task = Task.Factory.StartNew(() => this.InitializeViewModel(myViewModel));
task.ContinueWith(o => MyErrorHandler(task.Exception), TaskContinuationOptions.OnlyOnFaulted);
and check a lot of other similar questions on StackOverflow. But It is always the same - exception is not handled. It is not handled on these primitive code snippets! I think it is some magic here...
I work on .Net Framework 4.0
Meanwhile single way to handle exception that works for me is:
Task.Factory.StartNew(() =>
{
try
{
//do something that thrown exception
}
catch (Exception)
{
}
});
If you run that example code in Visual Studio, you will indeed get the message MyCustomException was unhandled by user code and Visual Studio will break in that line.
That does not mean that your exception is really unhandled. It just means that, by default, Visual Studio breaks on exceptions which are not handled inside the Task. You can verify this by running your application without debugging (Ctrl-F5); you will note that your exception gets handled as expected.
This issue is described in more detail in the following SO question:
Stop visual studio from breaking on exception in Tasks
Microsoft Visual Studio debugging facilities for managed code have an option "Just My Code". This option enabled forces debugger to break in immediately when an exception leaves user code (Task delegate in your example) and enters non-user code (TPL internal in your example). This feature was designed before introduction of TPL to make .NET applications debugging more comfortable with looking only at the code you have written and ignore other code, such as system calls. Just My Code hides non-user code so that it does not appear in the debugger windows. When you step, the debugger steps through any non-user code but does not stop in it.
But now in fact "Just My Code" feature interfere with TPL implementation.
There are four ways to deal with this issue:
Run your code without debugging.
Just ignoring of the Visual Studio debugger message about unhanded exception by continuation of program execution.
Disabling of "Just My Code" option in the Microsoft Visual Studio. This variant is recommended by Microsoft guy Danny Shih from Parallel Computing Platform team (PFX Team) http://blogs.msdn.com/b/pfxteam/archive/2010/01/11/faq-the-debugger-does-not-correctly-handle-task-exceptions.aspx.
Related
I set my Visual Studio Exception Settings to Break When 'Common Language Runtime Exceptions' are thrown.
I have numerous routines where I catch exceptions, handle them and continue. When I'm debugging my program, I trust that these exceptions have been correctly handled and do not want the debugger to stop on them.
How can I prevent the debugger from stopping on handled exceptions?
(Note, I want to break on all other CLR exceptions)
I thought DebuggerStepThrough would do the trick. However it doesn't. The following code stops on 'Method1();'
using System;
namespace ConsoleApp8
{
class Program
{
static void Main(string[] args)
{
Method1();
}
[System.Diagnostics.DebuggerStepThrough]
static void Method1()
{
try
{
throw new InvalidOperationException();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
}
-- Edit --
Kirk - I only throw exceptions in exceptional situations. I work with Visual Studio Tools for Office. This MS library often throws exceptions that can be handled and ignored.
I would like to handle certain exceptions thrown by another library but prevent the VS2017 debugger from stopping when these errors occur.
To be clear, these exceptions are usually COM Exceptions. I don't want the debugger to ignore ALL COM Exceptions. I only want the debugger to ignore COM Exceptions that I have caught and handled.
Is this possible?
The debugger can break execution at the point where an exception is thrown, so you may examine the exception before a handler is invoked. In the Exception Settings window (Debug > Windows > Exception Settings), expand the node for a category of exceptions, such as Common Language Runtime Exceptions. There you can change the behaviour.
I run into troubles using the Roslyn Scripting Engine. I get no exception handling when I run a script within a delegation.
Test that works as expected:
string script = #"var a=0; var b=2/a;";
var runner = CSharpScript.Create<object>(script);
var errors = runner.Compile();
Assert.IsTrue(errors.IsEmpty);
try
{
runner.RunAsync();
Assert.Fail("Where is the exception");
}
catch (System.Exception)
{
// everything is OK! Error thrown...
}
Result: No Assertion. The Exception was thrown.
Here's the text using a delegate object:
Unittest:
string script = #"var a=0; var b=2/a;";
var runner = CSharpScript.Create<object>(script);
var errors = runner.Compile();
var delegat = runner.CreateDelegate();
Assert.IsTrue(errors.IsEmpty);
try
{
delegat();
Assert.Fail("Where is the exception?");
}
catch (System.DivideByZeroException)
{
// everything is OK! Error thrown...
}
I got the fail message and no exception was thrown.
We cache the delegates to speed up the compilation and during a test we see that runtime exceptions are not thrown. So I wrote the test to reproduce this situation.
I can't find any hint in the docs which describes that there are no exceptions thrown during the invoke.
Can someone give me a pointer or a hint why this happens?
There are two issues with your code:
In the first version, you're catching Exception, which means that when the Assert.Fail is reached and throws AssertionException, that exception is then caught and ignored.
This means that there is no difference between RunAsync and delegate here, neither of them throws DivideByZeroException.
Both RunAsync and the ScriptRunner<T> delegate return Task. That means to actually wait for them to complete or to observe any exceptions, you need to use await. Once you do that, you will see the DivideByZeroException that you're expecting.
Your Main finishes execution before the scheduler gets a chance to invoke delegat. It is a task that will run asynchronously. You can see that when you inspect it in the debugger:
To force execution inside the scope of the try...catch, you can use this:
try
{
delegat().Wait();
}
catch(System.AggregateException ex)
{
/* the inner exception of ex will be your DivideByZeroException */
}
The correct type of exception to expect in this case is the AggregateException, see here why.
A solution with await is also possible:
await delegat();
but this will compile only when the containing method can be marked async which is not necessarily what you want (show more of the calling code to clarify).
Code sample:
using System;
using System.Threading.Tasks;
public class Program
{
public static void Main()
{
Console.WriteLine("Start");
Foo f = new Foo();
f.FooAsync();
}
public class Foo
{
public async void FooAsync()
{
try
{
await Task.Run(() =>
{
Console.WriteLine("Throwing");
throw new Exception();
});
}
catch (Exception)
{
Console.WriteLine("Caught");
}
}
}
}
The above code when run from C# fiddle or from the console on my PC prints:
Start
Throwing
Caught
C# Fiddle Example
However, when I run it from Visual Studio (F5 in debug mode), I get the following message:
I don't understand why I get "was not handled in user code" message from Visual Studio although running it from the console or C# fiddle is fine. Am I missing something obvious?
UPDATE
I've tried waiting on the task f.FooAsync().Wait(); in Main, but the exception is still reported as being unhandled (same error message).
First, what's special about this exception is that it's being thrown from Task.Run and for that scope, the exception really isn't handled by user-code.
The framework catches and stores the exception in the returned task for you to handle later, if you fail to do that it's an unobserved task exception (which in .Net 4.0 would've crashed the application).
The issue here is the "Enable Just My Code" feature in the settings. When the feature is turned on the debugger breaks on exceptions when you leave user-code and enter framework-code and at that point the exception really wasn't handled.
If you turn that feature off the debugger will not break on that exception as it will follow your code into the framework and see the exception being handled and stored in the task. The exception will then be re-thrown when you await the task and be handled by your code.
Since the handling that actually matters is the one being done by the framework, this is an even simpler example:
public static void Main()
{
Task.Run(() =>
{
throw new Exception();
});
Console.ReadLine();
}
With "Enable Just My Code" turned on the debugger will break on the exception, without it the debugger will not.
I am sure I am doinig something wrong, but when I try this example of the new threading task exception handling I keep getting the exception unhandled by user code. The whole point of the code is to show an example of how to catch errors in tasks.
Link: Task Exception Example
static void Main(string[] args)
{
var task1 = Task.Factory.StartNew(() =>
{
throw new MyCustomException("I'm bad, but not too bad!");
});
try
{
task1.Wait();
}
catch (AggregateException ae)
{
// Assume we know what's going on with this particular exception.
// Rethrow anything else. AggregateException.Handle provides
// another way to express this. See later example.
foreach (var e in ae.InnerExceptions)
{
if (e is MyCustomException)
{
Console.WriteLine(e.Message);
}
else
{
throw;
}
}
}
}
Most likely user error just not sure what (Using Visual Studio 2012);
From the page you cited:
Note
When "Just My Code" is enabled, Visual Studio in some cases will
break on the line that throws the exception and display an error
message that says "exception not handled by user code." This error is
benign. You can press F5 to continue and see the exception-handling
behavior that is demonstrated in these examples. To prevent Visual
Studio from breaking on the first error, just uncheck the "Just My
Code" checkbox under Tools, Options, Debugging, General.
I have a Windows Console application built in Visual Studio 2010 and it keeps crashing but the error is not caught by the visual studio debugging tool nor by try/catch statements in my code.
I have managed to locate the WER file on my system and would like to be able to understand the contents of the file so I can pinpoint exactally what is causing the unhandled exception.
I would be greatful if anyone can offer some idea on how I can use the following information to locate the process causing me this problem and also what the exception may be...
The information from the WER file is:
Version=1
EventType=APPCRASH
EventTime=129973086237604286
ReportType=2
Consent=1
ReportIdentifier=91331e8b-2dc8-11e2-977b-080027f7e5bb
IntegratorReportIdentifier=91331e8a-2dc8-11e2-977b-080027f7e5bb
WOW64=1
Response.type=4
Sig[0].Name=Application Name
Sig[0].Value=SAGE_TESTING.vshost.exe
Sig[1].Name=Application Version
Sig[1].Value=10.0.30319.1
Sig[2].Name=Application Timestamp
Sig[2].Value=4ba2084b
Sig[3].Name=Fault Module Name
Sig[3].Value=ntdll.dll
Sig[4].Name=Fault Module Version
Sig[4].Value=6.1.7600.16385
Sig[5].Name=Fault Module Timestamp
Sig[5].Value=4a5bdb3b
Sig[6].Name=Exception Code
Sig[6].Value=c015000f
Sig[7].Name=Exception Offset
Sig[7].Value=000845bb
DynamicSig[1].Name=OS Version
DynamicSig[1].Value=6.1.7600.2.0.0.272.7
DynamicSig[2].Name=Locale ID
DynamicSig[2].Value=2057
DynamicSig[22].Name=Additional Information 1
DynamicSig[22].Value=0a9e
DynamicSig[23].Name=Additional Information 2
DynamicSig[23].Value=0a9e372d3b4ad19135b953a78882e789
DynamicSig[24].Name=Additional Information 3
DynamicSig[24].Value=0a9e
DynamicSig[25].Name=Additional Information 4
DynamicSig[25].Value=0a9e372d3b4ad19135b953a78882e789
Here is the section of code I believe to be causing the exception to be thrown:
//Data from the project linked to the split data
if (oSplitData.Project != null)
{
oProject = oSplitData.Project as SageDataObject190.Project;
oBasicDetail.ProjectID = oProject.ProjectID;
oBasicDetail.ProjectReference = oProject.Reference.ToString();
}
else
{
oBasicDetail.ProjectID = -1;
oBasicDetail.ProjectReference = "NO_PROJECT";
}
To add to all the above I seem to have found that there is a general exception that is being thrown but it doesn't help me out much - if anyone can put some light on this it would be great:
Unhandled exception at 0x78bc7361 in SAGE_TESTING.exe: 0xC0000005: Access violation reading location 0xfeeefeee.
If your program is multi-threaded and the exception is thrown in one of the spawned threads, the Exception may not be caught depending on how you do exception handling in your program.
You can add a catch-all exception handler like this:
class Program
{
static void Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionHandler;
// Your code here
}
static void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs e)
{
Console.WriteLine(e.ExceptionObject.ToString());
Environment.Exit(1);
}
}
UPDATE
Based on the code you posted, here are some things to look at
Put a try/catch block around the code you posted.
Are you sure that oSplitData is not null?
In the following line, oProject will be null if oSplitData.Project is not of type SageDataObject190.Project. Test for null.
oProject = oSplitData.Project as SageDataObject190.Project;
You are probably dealing with so-called corrupted state exceptions. These exceptions corrupt the process in a way so it is usually more safe to kill the process since it is very difficult to impossible to recover from such an error, even if it would be only for running a short catch-clause. Examples are StackOverflowExceptions, OutOfMemoryExceptions or AccessViolationExceptions.
There is an extensive and generally interesting explanation on corrupted state exceptions in this article.
What is helpful on getting a hand on such exceptions is to use DebugDiag. With this tool from Microsoft (download on this page) you can define a crash rule which generates a crashdump for your failed process. You can easily open these dump files in Visual Studio, where you may find the source of the exception that lead to the failure. This is not guaranteed but it often helped me in the past to nail down some nasty errors.
Are you invoking non-managed C++ or other code?
I'd try something like
static void Main()
{
try
{
DoSomethingUseful() ;
}
catch ( Exception e )
{
// managed exceptions caught here
}
catch
{
// non-managed C++ or other code can throw non-exception objects
// they are caught here.
}
return ;
}
See Will CLR handle both CLS-Complaint and non-CLS complaint exceptions?
Also C++ try, catch and throw statements at msdn: http://msdn.microsoft.com/en-us/library/6dekhbbc(v=vs.100).aspx
And MSIL opcode throw (0x7A) allows the throwing any object reference. C#, however, does not allow it.
But it looks like they improved things with .Net 2.0 and started wrapping oddball stuff in an RuntimeWrappedException.