<p>I'm working on a project using the <a href="http://antlr.org" rel="noreferrer">ANTLR</a> parser library for C#.  I've built a grammar to parse some text and it works well.  However, when the parser comes across an illegal or unexpected token, it throws one of many exceptions.  The problem is that in some cases (not all) that my try/catch block won't catch it and instead stops execution as an unhandled exception.</p>

<p>The issue for me is that I can't replicate this issue anywhere else but in my full code.  The call stack shows that the exception definitely occurs within my try/catch(Exception) block.  The only thing I can think of is that there are a few ANTLR assembly calls that occur between my code and the code throwing the exception and this library does not have debugging enabled, so I can't step through it.  I wonder if non-debuggable assemblies inhibit exception bubbling?  The call stack looks like this; external assembly calls are in Antlr.Runtime:</p>

<pre>
    Expl.Itinerary.dll!TimeDefLexer.mTokens() Line 1213 C#
    Antlr3.Runtime.dll!Antlr.Runtime.Lexer.NextToken() + 0xfc bytes 
    Antlr3.Runtime.dll!Antlr.Runtime.CommonTokenStream.FillBuffer() + 0x22c bytes   
    Antlr3.Runtime.dll!Antlr.Runtime.CommonTokenStream.LT(int k = 1) + 0x68 bytes
    Expl.Itinerary.dll!TimeDefParser.prog() Line 109 + 0x17 bytes   C#
    Expl.Itinerary.dll!Expl.Itinerary.TDLParser.Parse(string Text = "", Expl.Itinerary.IItinerary Itinerary = {Expl.Itinerary.MemoryItinerary}) Line 17 + 0xa bytes C#
</pre>

<p>The code snippet from the bottom-most call in Parse() looks like:</p>

<pre><code>     try {
        // Execution stopped at parser.prog()
        TimeDefParser.prog_return prog_ret = parser.prog();
        return prog_ret == null ? null : prog_ret.value;
     }
     catch (Exception ex) {
        throw new ParserException(ex.Message, ex);
     }
</code></pre>

<p>To me, a catch (Exception) clause should've captured any exception whatsoever.  Is there any reason why it wouldn't?</p>

<p><strong>Update:</strong> I traced through the external assembly with Reflector and found no evidence of threading whatsoever.  The assembly seems to just be a runtime utility class for ANTLR's generated code.  The exception thrown is from the TimeDefLexer.mTokens() method and its type is NoViableAltException, which derives from RecognitionException -> Exception.  This exception is thrown when the lexer cannot understand the next token in the stream; in other words, invalid input.  This exception is SUPPOSED to happen, however it should've been caught by my try/catch block.</p>

<p>Also, the rethrowing of ParserException is really irrelevant to this situation.  That is a layer of abstraction that takes any exception during parse and convert to my own ParserException.  The exception handling problem I'm experiencing is never reaching that line of code.  In fact, I commented out the "throw new ParserException" portion and still received the same result.</p>

<p>One more thing, I modified the original try/catch block in question to instead catch NoViableAltException, eliminating any inheritance confusion.  I still received the same result.</p>

<p>Someone once suggested that sometimes VS is overactive on catching handled exceptions when in debug mode, but this issue also happens in release mode.</p>

<p>Man, I'm still stumped!  I hadn't mentioned it before, but I'm running VS 2008 and all my code is 3.5.  The external assembly is 2.0.  Also, some of my code subclasses a class in the 2.0 assembly.  Could a version mismatch cause this issue?</p>

<p><strong>Update 2:</strong> I was able to eliminate the .NET version conflict by porting relevant portions of my .NET 3.5 code to a .NET 2.0 project and replicate the same scenario.  I was able to replicate the same unhandled exception when running consistently in .NET 2.0.</p>

<p>I learned that ANTLR has recently released 3.1.  So, I upgraded from 3.0.1 and retried.  It turns out the generated code is a little refactored, but the same unhandled exception occurs in my test cases.</p>

<p><strong>Update 3:</strong>
I've replicated this scenario in a <a href="http://www.explodingcoder.com/cms/files/TestAntlr-3.1.zip" rel="noreferrer">simplified VS 2008 project</a>.  Feel free to download and inspect the project for yourself.  I've applied all the great suggestions, but have not been able to overcome this obstacle yet.</p>

<p>If you can find a workaround, please do share your findings.  Thanks again!</p>

<hr>

<p>Thank you, but VS 2008 automatically breaks on unhandled exceptions.  Also, I don't have a Debug->Exceptions dialog.  The NoViableAltException that is thrown is fully intended, and designed to be caught by user code.  Since it is not caught as expected, program execution halts unexpectedly as an unhandled exception.</p>

<p>The exception thrown is derived from Exception and there is no multi-threading going on with ANTLR.</p>

[{'answer_id': 36029, 'author': 'Daniel Auger', 'author_id': 1644, 'author_profile': 'https://Stackoverflow.com/users/1644', 'pm_score': 2, 'selected': False, 'text': '<p>Is it possible that the exception is being thrown in another thread? Obviously your calling code is single threaded, but maybe the library you are consuming is doing some multithreaded operations under the covers.</p>\n'}, {'answer_id': 36047, 'author': 'ljs', 'author_id': 3394, 'author_profile': 'https://Stackoverflow.com/users/3394', 'pm_score': 3, 'selected': False, 'text': "<p>Regardless of whether the assembly has been compiled as a release build the exception should certainly 'bubble' up to the caller, there's no reason an assembly not being compiled in debug mode should have any affect on that.</p>\n\n<p>I'd agree with Daniel is suggesting that perhaps the exception is occurring on a separate thread - try hooking the thread exception event in Application.ThreadException. This should be raised when any unhandled thread exception occurs. You could adapt your code thus:-</p>\n\n<pre><code>using System.Threading;\n\n...\n\nvoid Application_ThreadException(object sender, ThreadExceptionEventArgs e) {\n  throw new ParserException(e.Exception.Message, e.Exception);\n}    \n\n ...\n\n var exceptionHandler = \n    new ThreadExceptionEventHandler(Application_ThreadException);\n Application.ThreadException += exceptionHandler;\n try {\n    // Execution stopped at parser.prog()\n    TimeDefParser.prog_return prog_ret = parser.prog();\n    return prog_ret == null ? null : prog_ret.value;\n }\n catch (Exception ex) {\n    throw new ParserException(ex.Message, ex);\n }\n finally {\n    Application.ThreadException -= exceptionHandler;\n }\n</code></pre>\n"}, {'answer_id': 36048, 'author': 'Kibbee', 'author_id': 1862, 'author_profile': 'https://Stackoverflow.com/users/1862', 'pm_score': 2, 'selected': False, 'text': "<p>You can set up VS.Net to break as soon as any exception occurs. Just run your project in debug mode, and it will stop as soon as the exception is thrown.  Then you should have a better idea of why it isn't being caught.</p>\n<p>Also, you can put some code in to catch all unhandled exceptions.</p>\n<pre><code>Application.ThreadException += new ThreadExceptionEventHandler(ThreadExceptionHandler);\n\n // Catch all unhandled exceptions in all threads.\n AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionHandler);\n</code></pre>\n"}, {'answer_id': 36051, 'author': 'ljs', 'author_id': 3394, 'author_profile': 'https://Stackoverflow.com/users/3394', 'pm_score': 1, 'selected': False, 'text': "<p>Oh and in reference to what Kibbee said; if you select Debug|Exceptions in VS and just click all the boxes in the 'thrown' column it should pick <em>everything</em> up AFAIK as a 'first chance exception', i.e. VS will indicate when the exception is <em>about</em> to be processed by everything else and break on the relevant code. This should help with debugging.</p>\n"}, {'answer_id': 36069, 'author': 'Quibblesome', 'author_id': 1143, 'author_profile': 'https://Stackoverflow.com/users/1143', 'pm_score': 0, 'selected': False, 'text': '<blockquote>\n  <p>"Also, you can put some code in to\n  catch all unhandled exceptions. Read\n  the link for more info, but the basics\n  are these two lines."</p>\n</blockquote>\n\n<p>This is false. This used to catch all unhandled exceptions in .NET 1.0/1.1 but it was a bug and it wasn\'t supposed to and it was fixed in .NET 2.0. </p>\n\n<pre><code>AppDomain.CurrentDomain.UnhandledException \n</code></pre>\n\n<p>Is only intended to be used as a last chance logging saloon so you can log the exception before the program exits. It wont catch the exception as of 2.0 onwards (although in .NET 2.0 at least there is a config value you can modify to make it act like 1.1 but it isn\'t recommended practice to use this.).</p>\n\n<p>Its worth noting that there are few exceptions that you <em>cannot</em> catch, such as StackOverflowException and OutOfMemoryException. Otherwise as other people have suggested it might be an exception in a background thread somewhere. Also I\'m pretty sure you can\'t catch some/all unmanaged/native exceptions either.</p>\n'}, {'answer_id': 36072, 'author': 'tbreffni', 'author_id': 637, 'author_profile': 'https://Stackoverflow.com/users/637', 'pm_score': 3, 'selected': False, 'text': '<p>Are you using .Net 1.0 or 1.1?  If so then catch(Exception ex) won\'t catch exceptions from unmanaged code.  You\'ll need to use catch {} instead.  See this article for further details:</p>\n\n<p><a href="http://www.netfxharmonics.com/2005/10/net-20-trycatch-and-trycatchexception/" rel="noreferrer">http://www.netfxharmonics.com/2005/10/net-20-trycatch-and-trycatchexception/</a></p>\n'}, {'answer_id': 36074, 'author': 'Mark Brackett', 'author_id': 2199, 'author_profile': 'https://Stackoverflow.com/users/2199', 'pm_score': 0, 'selected': False, 'text': "<p>I don't get it...your catch block just throws a new exception (with the same message). Meaning that your statement of:</p>\n\n<blockquote>\n  <p>The problem is that in some cases (not all) that my try/catch block won't catch it and instead stops execution as an unhandled exception.</p>\n</blockquote>\n\n<p>is exactly what is <em>expected</em> to happen.</p>\n"}, {'answer_id': 36083, 'author': 'flipdoubt', 'author_id': 470, 'author_profile': 'https://Stackoverflow.com/users/470', 'pm_score': 0, 'selected': False, 'text': '<p>I agree with <a href="https://stackoverflow.com/users/1644/daniel-auger">Daniel Auger</a> and <a href="https://stackoverflow.com/users/3394/kronoz">kronoz</a> that this smells like an exception that has something to do with threads. Beyond that, here are my other questions:</p>\n\n<ol>\n<li>What does the complete error message say? What kind of exception is it?</li>\n<li>Based on the stack trace you\'ve provided here, isn\'t the exception thrown by you code in TimeDefLexer.mTokens()?</li>\n</ol>\n'}, {'answer_id': 36898, 'author': 'Scott Dorman', 'author_id': 1559, 'author_profile': 'https://Stackoverflow.com/users/1559', 'pm_score': 1, 'selected': False, 'text': '<p>The best option sounds like setting Visual Studio to break on all unhandled exceptions (Debug -> Exceptions dialog, check the box for "Common Language Runtime Exceptions" and possibly the others as well). Then run your program in debug mode. When the ANTLR parser code throws an exception it should be caught by Visual Studio and allow you to see where it is occurring, the exception type, etc.</p>\n\n<p>Based on the description, the catch block appears to be correct, so one of several things could be happening:</p>\n\n<ol>\n<li>the parser is not actually throwing an exception</li>\n<li>the parser is ultimately throwing something that isn\'t deriving from System.Exception</li>\n<li>there is an exception being thrown on another thread that isn\'t being handled</li>\n</ol>\n\n<p>It sounds like you have potentially ruled out issue #3.</p>\n'}, {'answer_id': 37435, 'author': 'Orion Edwards', 'author_id': 234, 'author_profile': 'https://Stackoverflow.com/users/234', 'pm_score': 1, 'selected': False, 'text': '<blockquote>\n  <p>I traced through the external assembly with Reflector and found no evidence of threading whatsoever.</p>\n</blockquote>\n\n<p><strong>You can\'t find any threading does not mean there is no threading</strong></p>\n\n<p>.NET has a \'thread pool\' which is a set of \'spare\' threads that sit around mostly idle. Certain methods cause things to run in one of the thread pool threads so they don\'t block your main app.</p>\n\n<p>The blatant examples are things like <a href="http://msdn.microsoft.com/en-us/library/system.threading.threadpool.queueuserworkitem.aspx" rel="nofollow noreferrer">ThreadPool.QueueUserWorkItem</a>, but there are lots and lots of other things which can also run things in the thread pool that don\'t look so obvious, like <a href="http://msdn.microsoft.com/en-us/library/2e08f6yc.aspx" rel="nofollow noreferrer">Delegate.BeginInvoke</a></p>\n\n<p>Really, you need to <a href="https://stackoverflow.com/questions/36014/why-is-net-exception-not-caught-by-trycatch-block#36048">do what kibbee suggests</a>.</p>\n'}, {'answer_id': 38812, 'author': 'Steve Steiner', 'author_id': 3892, 'author_profile': 'https://Stackoverflow.com/users/3892', 'pm_score': 2, 'selected': False, 'text': '<blockquote>\n  <p>To me, a catch (Exception) clause should\'ve captured any exception whatsoever. Is there any reason why it wouldn\'t?</p>\n</blockquote>\n\n<p>The only possibility I can think of is that something else is catching it before you and handling it in a way that appears to be an uncaught exception (e.g. exiting the process).</p>\n\n<blockquote>\n  <p>my try/catch block won\'t catch it and instead stops execution as an unhandled exception.</p>\n</blockquote>\n\n<p>You need to find what is causing the exit process.  It might be something other than an unhandled exception.\nYou might try using the native debugger with a breakpoint set on "{,,kernel32.dll}ExitProcess".  Then use <a href="http://msdn.microsoft.com/en-us/library/bb190764(VS.80).aspx" rel="nofollow noreferrer">SOS</a> to determine what managed code is calling exit process.</p>\n'}, {'answer_id': 39606, 'author': 'spoulson', 'author_id': 3347, 'author_profile': 'https://Stackoverflow.com/users/3347', 'pm_score': 0, 'selected': False, 'text': '<p>I\'m not sure if I\'m being unclear, but if so, I\'m seeing the debugger halt execution with an "Unhandled Exception" of type NoViableAltException.  Initially, I didn\'t know anything about this Debug->Exceptions menu item because MS expects you, at VS install time, to commit to a profile when you have no idea how they are different.  Apparently, <a href="http://blogs.vertigo.com/personal/keithc/Blog/archive/2007/07/20/missing-menu-options-in-visual-studio-2005.aspx" rel="nofollow noreferrer">I was not on the C# dev profile and was missing this option</a>.  After finally debugging all thrown CLR exceptions, I was unfortunately unable to discover any new behavior leading to the reason for this unhandled exception issue.  All the exceptions thrown were expected and supposedly handled in a try/catch block.</p>\n\n<p>I reviewed the external assembly and there is no evidence of multithreading.  By that, I mean no reference exists to System.Threading and no delegates were used whatsoever.  I\'m familiar with that constitutes instantiating a thread.  I verify this by observing the Threads toolbox at the time of the unhandled exception to view there is only one running thread.</p>\n\n<p>I have an open issue with the ANTLR folks so perhaps they\'ve been able to tackle this issue before.  I\'ve been able to replicate it in a simple console app project using .NET 2.0 and 3.5 under VS 2008 and VS 2005.</p>\n\n<p>It\'s just a pain point because it forces my code to only work with known valid parser input.  Using an <code>IsValid()</code> method would be risky if it threw an unhandled exception based on user input.  I\'ll keep this question up to date when more is learned of this issue.</p>\n'}, {'answer_id': 39668, 'author': 'Cory Foy', 'author_id': 4083, 'author_profile': 'https://Stackoverflow.com/users/4083', 'pm_score': 0, 'selected': False, 'text': '<p>@spoulson,</p>\n\n<p>If you can replicate it, can you post it somewhere? One avenue you could try is usign WinDBG with the SOS extensions to run the app and catch the unhandled exception. It will break on the first chance exception (before the runtime tries to find a handler) and you can see at that point where it is coming from, and what thread.</p>\n\n<p>If you haven\'t used WinDBG before, it can be a little overwhelming, but here\'s a good tutorial:</p>\n\n<p><a href="http://blogs.msdn.com/johan/archive/2007/11/13/getting-started-with-windbg-part-i.aspx" rel="nofollow noreferrer"><a href="http://blogs.msdn.com/johan/archive/2007/11/13/getting-started-with-windbg-part-i.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/johan/archive/2007/11/13/getting-started-with-windbg-part-i.aspx</a></a></p>\n\n<p>Once you start up WinDBG, you can toggle the breaking of unhandled exceptions by going to Debug->Event Filters.</p>\n'}, {'answer_id': 39845, 'author': 'Eduardo Diaz', 'author_id': 3245, 'author_profile': 'https://Stackoverflow.com/users/3245', 'pm_score': 1, 'selected': False, 'text': '<p>have you tried to print (Console.WriteLine()) the exception inside the catch clause, and not use visual studio and run your application on console?</p>\n'}, {'answer_id': 39873, 'author': 'Shaun Austin', 'author_id': 1120, 'author_profile': 'https://Stackoverflow.com/users/1120', 'pm_score': 2, 'selected': False, 'text': '<p>Personally I\'m not convinced by the threading theory at all.</p>\n\n<p>The one time I\'ve seen this before, I was working with a library which also defined Exception and the usings I had meant that the actual Catch was referring to a different "Exception" type (if it had been fully qualified it was Company.Lib.Exception but it wasnt because of the using) so when it came to catching a normal exception that was being thrown (some kind of argument exception if I remember correctly) it just wouldn\'t catch it because the type didn\'t match.</p>\n\n<p>So in summary, is there another Exception type in a different namespace that is in a using in that class?</p>\n\n<p>EDIT: A quick way to check this is make sure in your catch clause you fully qualify the Exception type as "System.Exception" and give it a whirl!</p>\n\n<p>EDIT2: OK I\'ve tried the code and concede defeat for now. I\'ll have to have another look at it in the morning if no one has come up with a solution.</p>\n'}, {'answer_id': 40055, 'author': 'JamesSugrue', 'author_id': 1075, 'author_profile': 'https://Stackoverflow.com/users/1075', 'pm_score': 2, 'selected': False, 'text': "<p>I'm with @Shaun Austin - try wrapping the try with the fully qualified name</p>\n\n<pre><code>catch (System.Exception)\n</code></pre>\n\n<p>and see if that helps.Does the ANTLR doc say what Exceptions should be thrown?</p>\n"}, {'answer_id': 40612, 'author': 'Lasse V. Karlsen', 'author_id': 267, 'author_profile': 'https://Stackoverflow.com/users/267', 'pm_score': 2, 'selected': False, 'text': "<p>Hmm, I don't understand the problem. I downloaded and tried your example solution file.</p>\n\n<p>An exception is thrown in TimeDefLexer.cs, line 852, which is subsequently handled by the catch block in Program.cs that just says <em>Handled exception</em>.</p>\n\n<p>If I uncomment the catch block above it, it will enter that block instead.</p>\n\n<p>What seems to be the problem here?</p>\n\n<p>As Kibbee said, Visual Studio will stop on exceptions, but if you ask it to continue, the exception will get caught by your code.</p>\n"}, {'answer_id': 40828, 'author': 'Scott Nichols', 'author_id': 4299, 'author_profile': 'https://Stackoverflow.com/users/4299', 'pm_score': 2, 'selected': False, 'text': '<p>I downloaded the sample VS2008 project, and am a bit stumped here too.  I was able to get past the exceptions however, although probably not in a way that will work will great for you.  But here\'s what I found:</p>\n\n<p>This <a href="http://www.antlr.org:8080/pipermail/antlr-interest/2008-February/026657.html" rel="nofollow noreferrer">mailing list post</a> had a discussion of what looks to be the same issue you are experiencing.</p>\n\n<p>From there, I added a couple dummy classes in the main program.cs file:</p>\n\n<pre><code>class MyNoViableAltException : Exception\n{\n    public MyNoViableAltException()\n    {\n    }\n    public MyNoViableAltException(string grammarDecisionDescription, int decisionNumber, int stateNumber, Antlr.Runtime.IIntStream input)\n    {\n    }\n}\nclass MyEarlyExitException : Exception\n{\n    public MyEarlyExitException()\n    {\n    }\n\n    public MyEarlyExitException(int decisionNumber, Antlr.Runtime.IIntStream input)\n    {\n    }\n}\n</code></pre>\n\n<p>and then added the using lines into TimeDefParser.cs and TimeDefLexer.cs:</p>\n\n<pre><code>using NoViableAltException = MyNoViableAltException;\nusing EarlyExitException = NoViableAltException; \n</code></pre>\n\n<p>With that the exceptions would bubble into the fake exception classes and could be handled there, but there was still an exception being thrown in the mTokens method in TimeDefLexer.cs.  Wrapping that in a try catch in that class caught the exception:</p>\n\n<pre><code>            try\n            {\n                alt4 = dfa4.Predict(input);\n            }\n            catch\n            {\n            }\n</code></pre>\n\n<p>I really don\'t get why wrapping it in the internal method rather than where it is being called from handle the error if threading isn\'t in play, but anyways hopefully that will point someone smarter than me here in the right direction.</p>\n'}, {'answer_id': 41014, 'author': 'spoulson', 'author_id': 3347, 'author_profile': 'https://Stackoverflow.com/users/3347', 'pm_score': 0, 'selected': False, 'text': "<p>Wow, so of the reports so far, 2 worked correctly, and 1 experienced the issue I reported.  What are the versions of Windows, Visual Studio used and .NET framework with build numbers?</p>\n\n<p>I'm running XP SP2, VS 2008 Team Suite (9.0.30729.1 SP), C# 2008 (91899-270-92311015-60837), and .NET 3.5 SP1.</p>\n"}, {'answer_id': 41208, 'author': 'Steve Steiner', 'author_id': 3892, 'author_profile': 'https://Stackoverflow.com/users/3892', 'pm_score': 6, 'selected': True, 'text': '<p>I believe I understand the problem. The exception is being caught, the issue is confusion over the debugger\'s behavior and differences in the debugger settings among each person trying to repro it.</p>\n\n<p>In the 3rd case from your repro I believe you are getting the following message: "NoViableAltException was unhandled by user code" and a callstack that looks like this:</p>\n\n<pre>\n         [External Code]    \n    >   TestAntlr-3.1.exe!TimeDefLexer.mTokens() Line 852 + 0xe bytes   C#\n        [External Code] \n        TestAntlr-3.1.exe!TimeDefParser.prog() Line 141 + 0x14 bytes    C#\n        TestAntlr-3.1.exe!TestAntlr_3._1.Program.ParseTest(string Text = "foobar;") Line 49 + 0x9 bytes C#\n        TestAntlr-3.1.exe!TestAntlr_3._1.Program.Main(string[] args = {string[0x00000000]}) Line 30 + 0xb bytes C#\n        [External Code] \n</pre>\n\n<p>If you right click in the callstack window and run turn on show external code you see this:</p>\n\n<pre>\n        Antlr3.Runtime.dll!Antlr.Runtime.DFA.NoViableAlt(int s = 0x00000000, Antlr.Runtime.IIntStream input = {Antlr.Runtime.ANTLRStringStream}) + 0x80 bytes   \n        Antlr3.Runtime.dll!Antlr.Runtime.DFA.Predict(Antlr.Runtime.IIntStream input = {Antlr.Runtime.ANTLRStringStream}) + 0x21e bytes  \n    >   TestAntlr-3.1.exe!TimeDefLexer.mTokens() Line 852 + 0xe bytes   C#\n        Antlr3.Runtime.dll!Antlr.Runtime.Lexer.NextToken() + 0xc4 bytes \n        Antlr3.Runtime.dll!Antlr.Runtime.CommonTokenStream.FillBuffer() + 0x147 bytes   \n        Antlr3.Runtime.dll!Antlr.Runtime.CommonTokenStream.LT(int k = 0x00000001) + 0x2d bytes  \n        TestAntlr-3.1.exe!TimeDefParser.prog() Line 141 + 0x14 bytes    C#\n        TestAntlr-3.1.exe!TestAntlr_3._1.Program.ParseTest(string Text = "foobar;") Line 49 + 0x9 bytes C#\n        TestAntlr-3.1.exe!TestAntlr_3._1.Program.Main(string[] args = {string[0x00000000]}) Line 30 + 0xb bytes C#\n        [Native to Managed Transition]  \n        [Managed to Native Transition]  \n        mscorlib.dll!System.AppDomain.ExecuteAssembly(string assemblyFile, System.Security.Policy.Evidence assemblySecurity, string[] args) + 0x39 bytes    \n        Microsoft.VisualStudio.HostingProcess.Utilities.dll!Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() + 0x2b bytes  \n        mscorlib.dll!System.Threading.ThreadHelper.ThreadStart_Context(object state) + 0x3b bytes   \n        mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) + 0x81 bytes    \n        mscorlib.dll!System.Threading.ThreadHelper.ThreadStart() + 0x40 bytes\n</pre>\n\n<p>The debugger\'s message is telling you that an exception originating outside your code (from NoViableAlt) is going through code you own in TestAntlr-3.1.exe!TimeDefLexer.mTokens() without being handled.  </p>\n\n<p>The wording is confusing, but it does not mean the exception is uncaught. The debugger is letting you know that code you own mTokens()" needs to be robust against this exception being thrown through it.</p>\n\n<p>Things to play with to see how this looks for those who didn\'t repro the problem:</p>\n\n<ul>\n<li>Go to Tools/Options/Debugging and\nturn off "Enable Just My code\n(Managed only)". or option.</li>\n<li>Go to Debugger/Exceptions and turn off "User-unhandled" for\nCommon-Language Runtime Exceptions.</li>\n</ul>\n'}, {'answer_id': 41219, 'author': 'aku', 'author_id': 1196, 'author_profile': 'https://Stackoverflow.com/users/1196', 'pm_score': 2, 'selected': False, 'text': "<p>I downloaded your code and everything work as expected.  </p>\n\n<p>Visual Studio debugger correctly intercepts all exceptions. Catch blocks work as expected.  </p>\n\n<p>I'm running Windows 2003 server SP2, VS2008 Team Suite (9.0.30729.1 SP)  </p>\n\n<p>I tried to compile you project for .NET 2.0, 3.0 &amp; 3.5</p>\n\n<p>@Steve Steiner, debugger options you mentioned have nothing to do with this behavior.  </p>\n\n<p>I tried to play with these options with no visible effects - catch blocks managed to intercept all exceptions.</p>\n"}, {'answer_id': 41409, 'author': 'spoulson', 'author_id': 3347, 'author_profile': 'https://Stackoverflow.com/users/3347', 'pm_score': 1, 'selected': False, 'text': '<p>I believe Steve Steiner is correct.  When researching Steve\'s suggestions, I came across <a href="http://www.dotnetmonster.com/Uwe/Forum.aspx/vs-net-ide/4729/Disabling-Just-my-code-changes-Debug-Exceptions-dialog" rel="nofollow noreferrer">this thread</a> talking about the "Enable Just My Code" option in Tools|Options|Debugger|General.  It is suggested that the debugger will break in certain conditions when non-user code either throws or handles an exception.  I\'m not exactly sure why this even matters, or why the debugger specifically says the exception was unhandled when it really was.</p>\n\n<p>I was able to eliminate the false breaks by disabling the "Enable Just My Code" option.  This also changes the Debug|Exceptions dialog by removing the "User-handled" column as it no longer applies.  Or, you can just uncheck the "User-handled" box for CLR and get the same result.</p>\n\n<p>Bigtime thanks for the help everyone!</p>\n'}, {'answer_id': 630024, 'author': 'Dave Turvey', 'author_id': 18966, 'author_profile': 'https://Stackoverflow.com/users/18966', 'pm_score': 2, 'selected': False, 'text': '<p>Steve Steiner is correct that the exception is originating in the antlr library, passing through the mTokens() method and being caught in the antlr library. The problem is that this method is auto-generated by antlr. Therefore, any changes to handle the exception in mTokens() will be overwritten when your generate your parser/lexer classes. </p>\n\n<p>By default, antlr will log errors and try to recover parsing. You can override this so that the parser.prog() will throw an exception whenever an error is encountered. From your example code i think this is the behaviour you were expecting.</p>\n\n<p>Add this code to your grammer (.g) file. You will also need to turn off "Enable Just My Code" in the debugging menu.</p>\n\n<pre><code>@members {\n\n    public override Object RecoverFromMismatchedSet(IIntStream input,RecognitionException e,    BitSet follow)  \n    {\n        throw e;\n    }\n}\n\n@rulecatch {\n    catch (RecognitionException e) \n    {\n        throw e;\n    }\n}\n</code></pre>\n\n<p>This is my attempt at a C# version of the example given in the "Exiting the recogniser on first error" chapter of the "Definitive ANTLR Reference" book.</p>\n\n<p>Hope this is what you were looking for.</p>\n'}, {'answer_id': 8946874, 'author': 'Tony Schwartz', 'author_id': 1161343, 'author_profile': 'https://Stackoverflow.com/users/1161343', 'pm_score': 3, 'selected': False, 'text': '<p>I can tell you what\'s happening here...</p>\n\n<p>Visual Studio is breaking because it thinks the exception is unhandled.  What does unhandled mean?  Well, in Visual Studio, there is a setting in the Tools... Options... Debugging... General... "Enable Just My Code (Managed only)".  If this is checked and if the exception propagates out of your code and out to a stack frame associated with a method call that exists in an assembly which is "NOT YOUR CODE" (for example, Antlr), that is considered "unhandled".  I turn off that Enable Just My Code feature for this reason.  But, if you ask me, this is lame... let\'s say you do this:</p>\n\n<pre><code>ExternalClassNotMyCode c = new ExternalClassNotMyCode();\ntry {\n    c.doSomething( () =&gt; { throw new Exception(); } );\n}\ncatch ( Exception ex ) {}\n</code></pre>\n\n<p>doSomething calls your anonymous function there and that function throws an exception...</p>\n\n<p>Note that this is an "unhandled exception" according to Visual Studio if "Enable Just My Code" is on.  Also, note that it stops as if it were a breakpoint when in debug mode, but in a non-debugging or production environment, the code is perfectly valid and works as expected.  Also, if you just "continue" in the debugger, the app goes on it\'s merry way (it doesn\'t stop the thread).  It is considered "unhandled" because the exception propagates through a stack frame that is NOT in your code (i.e. in the external library).  If you ask me, this is lousy.  Please change this default behavior Microsoft.  This is a perfectly valid case of using Exceptions to control program logic.  Sometimes, you can\'t change the third party library to behave any other way, and this is a very useful way to accomplish many tasks.</p>\n\n<p>Take MyBatis for example, you can use this technique to stop processing records that are being collected by a call to SqlMapper.QueryWithRowDelegate.</p>\n'}, {'answer_id': 42293958, 'author': 'Daghan Karakasoglu', 'author_id': 2140434, 'author_profile': 'https://Stackoverflow.com/users/2140434', 'pm_score': 0, 'selected': False, 'text': '<p>If you are using com objects your project and try catch blocks not catch the exceptions you will be need disable Tools/Debugging/Break when exceptions cross AppDomain or managed/native boundaries(Managed only) option.</p>\n'}]
['https://Stackoverflow.com/questions/36014', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3347/']