views:

349

answers:

4

I have a statement inside a try/catch block, but the exception is not getting caught. Can anyone explain?

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

Line 139:                try
Line 140:                {
Line 141:                    return (int)Session["SelectedLeadID"];
Line 142:                }
Line 143:                catch (Exception ex)

Update This is an ASP.NET application. In the catch block, a new exception is thrown. The code you see is what is displayed on the ASP.NET error page.

+2  A: 

That catch block should catch the exception, but make sure there's no re-throwing in there.

Another small comment: I've been tricked quite a few times by VS, cause it breaks on exceptions like that while running in debug-mode. Try to simply press 'continue' or 'F5' and see if your application doesn't work anyway :)

cwap
No, unfortunately it does break. I do re-throw, but I would expect the application to only break further up the call stack?
avesse
Remember to rethrow the right way :) http://stackoverflow.com/questions/178456/what-is-the-proper-way-to-re-throw-an-exception-in-c
cwap
A: 

I suspect you're going to need to add more detail - that isn't reproducible just from your code. In particular (as already noted) we'd need to see inside the catch, and verify that the exception is actually being thrown from inside the try and not somewhere else.

Other possibilities:

  • you have dodgy code inside the exception handler that is itself throwing an exception
  • you have a dodgy Dispose() that is getting called (using etc)
  • you are in .NET 1.1 and the thing getting thrown (in code not shown) isn't an Exception, but some other object
Marc Gravell
A: 

If it is only the debugger breaking on the exception and you are using VS2005 or above, you might want to check under Debug->Exceptions... if any of the Common-Language-Runtime-Exceptions are activated. If so, the debugger will always catch the exceptions first, but you are allowed to continue.

To revert to normal execution, simply uncheck the apropriate exceptions from the list.

Frank Bollack
A: 

The code looks terribly ugly IMO. For there to be something in the catch() block means you are going to have another return ... statement which AFAIK you should always have a single return statement at the end of each function to make following code easier.

i.e. maybe your code should look like

public int Function()
{
  int leadID = 0;
  try
  {
    int leadID = (int)Session["SelectedLeadID"];
  }
  catch (Exception ex)
  {
    ...
  }
  return leadID
}

Single exit points are supposed to make the code easier to follow, I guess? Anyway, to get any useful help you have to post more of the function.

mrnye