Background: I have a async call, that somewhere deep down throws an exception... In my real application, it is a plugin that is running async, so I would like to wrap the exception and decorate the exception with the plugin name that the exception originates from.  But .Net throws away the outer exception, so additional details are lost,  I have made an example windows forms application with two buttons, and setup a general exception handler  Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException); application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);   Then one button:  private async void buttonThrowAndWrapExceptionAsync_Click(object sender, EventArgs e) {     _textBoxToSetTextOnGivenLastCall = textBox1;     try     {         await Task.Run(() =&gt;             ThrowExceptionA());     }     catch (Exception a)     {         throw new Exception("B", a);     } }   the other button:  private async void buttonThrowAndRethrowNewExceptionAsync_Click(object sender, EventArgs e) {     _textBoxToSetTextOnGivenLastCall = textBox2;     try     {         await Task.Run(() =&gt;             ThrowExceptionA());     }     catch (Exception)     {         throw new Exception("B");     } }   When I   throw new Exception("B", a);    in the context, Exception "A" occurs in the Application_ThreadException callback with no trace of 'B'... B does never appear, this is not what I would expect.  When I   throw new Exception("B");   Exception "B" appears in Application_ThreadException, and Exception "A" does not appear, this is to me understandable  In my 'real' application, I am contemplating making a 'hack' and just adding "A".ToString() to my "B" exception, but I know it is pretty bad, and I am sure we have lots of logic expecting to be able to wrap exceptions  BTW... using a background worker with exception handling in OnComplete works in the same way as the 'async' code here...  The example can be found here:    EDIT: After viewing the suggested  wich is simelar, and provides an answer to why, I am actually more interested in stopping this behaviour.  For now I have made an ugly hack... When Throwing my wrapper Exception, I wrap the wrapper B in a new Exception ProtectedFromASyncUnfoldException  throw new ProtectedFromASyncUnfoldException(new Exception("B", a));   This breaks the normal behaviour of InnerExceptions... and is not really what I wan't to do... any better sollutions?  Here's the Hack class:  public class ProtectedFromASyncUnfoldException : Exception {     public Exception InternalException { get;  }     public ProtectedFromASyncUnfoldException() {    }      public ProtectedFromASyncUnfoldException(string message)          : base(message) {   }      /// &lt;summary&gt;     /// Hack of exception.     /// Setting InternalException instead of innerException      /// to avoid strange behaviour of async exception handling in windows forms     /// that otherwise throws away all but the base exception     /// &lt;/summary&gt;     /// &lt;param name="message"&gt;&lt;/param&gt;     /// &lt;param name="innerException"&gt;transformed to InternalException&lt;/param&gt;     public ProtectedFromASyncUnfoldException(string message, Exception innerException)          : base(message)     {         InternalException = innerException;     }      public ProtectedFromASyncUnfoldException(Exception innerException)          : this(innerException.Message, innerException) { }      protected ProtectedFromASyncUnfoldException(SerializationInfo info, StreamingContext context)          : base(info, context) { }      public override string ToString()     {         return base.ToString()              + Environment.NewLine              + Environment.NewLine              + "---------------------"              + InternalException?.ToString();     } }
121911
I'm seeing some wierd behaviour when throwing exceptions and catching them in the Application.ThreadException event handler.  Basically whats happening in the sample below is that an exception is thrown in the DoWork event handler of a BackgroundWorker. The RunWorkerCompleted event handler rethrows a new exception with the original as the inner exception.  Why does the inner exception show up in the ThreadException event handler and not the acutal exception being thrown? If I do not provide an inner exception in the RunWorkerCompleted event handler, the correct exception will show up.  using System; using System.Windows.Forms; using System.ComponentModel;  namespace WierdExceptionApp {     class WierdExceptionForm : Form     {         BackgroundWorker worker = new BackgroundWorker();          public WierdExceptionForm()         {             worker.DoWork += new DoWorkEventHandler(worker_DoWork);             worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);             worker.RunWorkerAsync();         }          void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)         {             if (e.Error != null)             {                 throw new Exception("worker_RunWorkerCompleted", e.Error);             }         }          void worker_DoWork(object sender, DoWorkEventArgs e)         {             throw new Exception("worker_DoWork");         }          [STAThread]         static void Main()         {             Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);             Application.Run(new WierdExceptionForm());         }          static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)         {             MessageBox.Show(e.Exception.Message);         }    } }
120685
It seems to me that a lot of my debugging time is spent chasing down null-reference exceptions in complex statements. For instance:  For Each game As IHomeGame in _GamesToOpen.GetIterator()   Why, when I get a NullReferenceException, can I get the line number in the stack trace, but not the name of the object that equals null. In other words, why:  Object reference not set to an instance of an object.   instead of  _GamesToOpen is not set to an instance of an object.   or  Anonymous object returned by _GamesToOpen.GetIterator() is null.   or  game was set to null.   Is this strictly a design choice, meant to protect the anonymity of the code or is there a compelling reason in compiler design not to include this information in the debug-time exception?
12521
What are the best practices to consider when catching exceptions and re-throwing them? I want to make sure that the Exception object's InnerException and stack trace are preserved. Is there a difference between the following code blocks in the way they handle this?  try {     //some code } catch (Exception ex) {     throw ex; }   Vs:  try {     //some code } catch {     throw; }
89434
I am calling, through reflection, a method which may cause an exception. How can I pass the exception to my caller without the wrapper reflection puts around it? I am rethrowing the InnerException, but this destroys the stack trace. Example code:  public void test1() {     // Throw an exception for testing purposes     throw new ArgumentException("test1"); }  void test2() {     try     {         MethodInfo mi = typeof(Program).GetMethod("test1");         mi.Invoke(this, null);     }     catch (TargetInvocationException tiex)     {         // Throw the new exception         throw tiex.InnerException;     } }
68683
I don't want a discussion about when to and not to throw exceptions. I wish to resolve a simple issue. 99% of the time the argument for not throwing exceptions revolves around them being slow while the other side claims (with benchmark test) that the speed is not the issue. I've read numerous blogs, articles, and posts pertaining one side or the other. So which is it?  Some links from the answers: , , .
15838
Is there a typedef equivalent in C#, or someway to get some sort of similar behaviour? I've done some googling, but everywhere I look seems to be negative. Currently I have a situation similar to the following:  class GenericClass&lt;T&gt;  {     public event EventHandler&lt;EventData&gt; MyEvent;     public class EventData : EventArgs { /* snip */ }     // ... snip }   Now, it doesn't take a rocket scientist to figure out that this can very quickly lead to a lot of typing (apologies for the horrible pun) when trying to implement a handler for that event. It'd end up being something like this:  GenericClass&lt;int&gt; gcInt = new GenericClass&lt;int&gt;; gcInt.MyEvent += new EventHandler&lt;GenericClass&lt;int&gt;.EventData&gt;(gcInt_MyEvent); // ...  private void gcInt_MyEvent(object sender, GenericClass&lt;int&gt;.EventData e) {     throw new NotImplementedException(); }   Except, in my case, I was already using a complex type, not just an int. It'd be nice if it were possible to simplify this a little...  Edit: ie. perhaps typedefing the EventHandler instead of needing to redefine it to get similar behaviour.
117655
I have written a test class that covers 86% leaving out the apexpages.addmessage () in catch block, but majorly it throws the validation exceptions on that object when I try to update a record.(Here I am updating case status to closed and I have some custom fields to be filled out while closing the case).  My test class has 2 methods. 1st method is having the case with all the fields filled this covers all the code except catch block and 2nd method without the required fields while closing the case and even though it doesn't cover my test class to full 100%   In my case I am updating the case status to closed and while closing the case I have 2 custom fields that should not be "null" 1. xyz1__c and 2.xyz2__c (Their are validation rules written on the case object and these throwing me the exceptions if these fields are null while updating the case) I am not sure how to cover the validation exception in catch block in Test class   Can someone please provide any suggestions .  Apex controller  public with sharing class OCaseComment {     public String test2 {get;set;}     public String test1 {get;set;}     public string status {get;set;}     public casecomment ca;     public case c;     public ID caseId;     public pagereference save() {         caseId = ApexPages.currentPage().getParameters().get('caseid');         system.debug('case id entered' + caseId);         ca = new casecomment();         ca.ParentId = caseId;         ca.commentbody = 'question:' + test1 + '\n' + 'solution:' + test2;         ca.IsPublished = true;         list&lt;case&gt; c = [select Status, xyz1__c, xyz2__c from case where ID =: caseId];         list&lt;case&gt; cg = new list&lt;case&gt;();         for (case cd : c) {             cd.Status = 'Closed';             cg.add(cd);         }         try {             if (cg.size() &gt; 0 &amp;&amp; cg[0].xyz1__c != null &amp;&amp; cg[0].xyz2__c != null) {                 insert ca;             }             update cg;             status = 'saved';             system.debug('status value' + status);         } catch (DmlException d) {             Apexpages.addMessage(new ApexPages.message(Apexpages.Severity.Error, d.getMessage()));             status = 'unsaved';         }         return null;     } }   Test class   @isTest public class TestClassOCaseComment {     @isTest public static void withcaseid() {         case c = new         case (status = 'New', Origin = 'Phone', xyz1__c = 'Stats', xyz2__c = 'Issues');         insert c;         case ca = [select id, status, xyz2__c from             case where status = 'New'         ];         Test.setCurrentPage(page.SCaseComments);         OCaseComment cs = new OCaseComment();         cs.Test1 = ('test1');         cs.Test2 = ('test2');         apexpages.currentPage().getparameters().put('caseid', ca.id);         if (ca.id != null) {             cs.save();         }         casecomment cm = [select commentbody, isPublished from casecomment where parentid =: ca.Id];         string str = 'Question:' + cs.test1 + '\n' + 'Solution:' + cs.test2;         system.assertEquals(str, cm.CommentBody);         system.assert(true, cm.ispublished);         case g = [select Status from             case where ID = :                 ca.Id         ];         system.assertEquals('Closed', g.status);     }     @isTest static void caseWithoutproduct() {         try {             case c = new             case (status = 'New', Origin = 'Phone', xyz2__c = 'Issues');             insert c;             pagereference pr = page.SCaseComments;             pr.getParameters().put('caseid', c.Id);             test.setCurrentPage(pr);             OCaseComment cc = new OCaseComment();             cc.save();         } catch (Exception e) {             System.Assert(e.getMessage().contains('FIELD_CUSTOM_VALIDATION_EXCEPTION'));             System.Assert(e.getMessage().contains('xyz1__c'));         }     } }
92456
Alright, I have been doing the following (variable names have been changed):   FileInputStream fis = null; try {     fis = new FileInputStream(file);      ... process ...  } catch (IOException e) {     ... handle error ... } finally {     if (fis != null)         fis.close(); }    Recently, I started using FindBugs, which suggests that I am not properly closing streams.  I decide to see if there's anything that can be done with a finally{} block, and then I see, oh yeah, close() can throw IOException.  What are people supposed to do here?  The Java libraries throw too many checked exceptions.
118194
I've seen the following code many times:  try {     ... // some code } catch (Exception ex) {     ... // Do something     throw new CustomException(ex);      // or     // throw;      // or     // throw ex; }   Can you please explain the purpose of re-throwing an exception? Is it following a pattern/best practice in exception handling? (I've read somewhere that it's called "Caller Inform" pattern?)
42797
I have a WinForms form that won't close. In OnFormClosing, e.Cancel is set to true. I am guessing that some object in my application has bound to the Closing or FormClosing event, and is blocking the close. To find out, I'd like to determine what delegates are bound to one of these events.  Is there a way to determine the list of handlers bound to an event? Ideally I would do this via the Visual Studio debugger, but can write code in the application to find the handlers if necessary. Understanding that an event is like a hidden private field, I've navigated through the Debugger to the "Non-Public Fields" for the "Windows.Forms.Form" ancestor of my form, but to no avail.
55107
What is the difference between anonymous methods of C# 2.0 and lambda expressions of C# 3.0.?
29653
I know Googling I can find an appropriate answer, but I prefer listening to your personal (and maybe technical) opinions. What is the main reason of the difference between Java and C# in throwing exceptions? In Java the signature of a method that throws an exception has to use the "throws" keyword, while in C# you don't know in compilation time if an exception could be thrown.
95328
Why don't we use "to generate" or "to get"?  E.g.: "External component has thrown an exception", "JavaScript had just thrown an error straight away", "Instances of Error objects are thrown when runtime errors occur".
10226
I have a general exception handler, Application_error in my global.asax where I'm trying to isolate all the uncaught exceptions on all my many pages. I don't want to use Page_error to catch exception because it's inefficient to call that on so many pages. So where in the exception can I find what page actually caused the exception?
18207
If I throw a JavaScript exception myself (eg, throw "AArrggg"), how can I get the stack trace (in Firebug or otherwise)?  Right now I just get the message.  edit: As many people below have posted, it is possible to get a stack trace for a JavaScript exception but I want to get a stack trace for my exceptions.  For example:  function foo() {     bar(2); } function bar(n) {     if (n &lt; 2)         throw "Oh no! 'n' is too small!"     bar(n-1); }   When foo is called, I want to get a stack trace which includes the calls to foo, bar, bar.
86786
I have a problem with my trigger. In Sandbox, everything works fine. When I deploy it to production, I receive multiple exceptions - which is really strange, because I got angry and put the whole code in &quot;try&quot; block. When I put everything in &quot;try&quot; block, it shouldn't be possible not to catch an exception! This is how my code looks: trigger UpdateLeadField on Lead (before insert, before update) {      //debugging in progress     try{         if(Trigger.New[0].SomeField__c==NULL)         {             for(Lead obj: trigger.new)                 obj.SomeField__c = obj.OwnerId;             return;         }              if (Trigger.New[0].OwnerId != Trigger.Old[0].OwnerId)          {             for(Lead obj: trigger.new)             {                 if(Trigger.New[0].SomeField__c==NULL || [SELECT Name FROM UserRole Where Id = :[SELECT Id, UserRoleId FROM User WHERE Id = :obj.OwnerId][0].UserRoleId].Name == 'Some role')                 obj.SomeField__c = obj.OwnerId;             }         }     }     catch (Exception e)     {         System.debug(e);     } }  The main problem seems to be with Web-to-Lead - When deployed, it stops working. The exception:  Apex script unhandled trigger exception by user/organization: 005C00000XXXXXX/00XXXXX0000LXXQ UpdateLeadField: data changed by trigger for field Some field: id value of incorrect type: 00GC00000XXXXXqMAC  &quot;Some field&quot; is a lookup field.
52565
I'm currently using log4net in my ASP.NET MVC application to log exceptions.  The way I'm doing this is by having all my controllers inherit from a BaseController class.  In the BaseController's OnActionExecuting event, I log any exceptions that may have occurred:  protected override void OnActionExecuted(ActionExecutedContext filterContext) {     // Log any exceptions     ILog log = LogManager.GetLogger(filterContext.Controller.GetType());      if (filterContext.Exception != null)     {         log.Error("Unhandled exception: " + filterContext.Exception.Message +             ". Stack trace: " + filterContext.Exception.StackTrace,              filterContext.Exception);     } }   This works great if an unhandled exception occurred during a controller action.  As for 404 errors, I have a custom error set up in my web.config like so:  &lt;customErrors mode="On"&gt;     &lt;error statusCode="404" redirect="~/page-not-found"/&gt; &lt;/customErrors&gt;   And in the controller action that handles the "page-not-found" url, I log the original url being requested:  [AcceptVerbs(HttpVerbs.Get)] public ActionResult PageNotFound() {     log.Warn("404 page not found - " + Utils.SafeString(Request.QueryString["aspxerrorpath"]));      return View(); }   And this also works.  The problem that I'm having is how to log errors that are on the .aspx pages themselves.  Let's say I have a compilation error on one of the pages or some inline code that will throw an exception:  &lt;% ThisIsNotAValidFunction(); %&gt; &lt;% throw new Exception("help!"); %&gt;   It appears that the HandleError attribute is correctly rerouting this to my Error.aspx page in the Shared folder, but it is definitely not being caught by my BaseController's OnActionExecuted method.  I was thinking I could maybe put the logging code on the Error.aspx page itself, but I'm unsure of how to retrieve the error information at that level.