11

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.

4
  • 9
    You haven't shown what's in the catch block - for example, is there a "throw;" statement? Commented Oct 27, 2009 at 12:24
  • Show the full code of the try/catch block Commented Oct 27, 2009 at 12:35
  • Yes, at the moment it simply throws the exception as the InnerException of a new Exception - logging will be added later. Commented Oct 27, 2009 at 12:40
  • I realise this was a long time ago, but this isn't a nice way to do this you should be using Int32.TryParse which would handle that it might not be able to set the int value. Commented Mar 8, 2016 at 8:52

7 Answers 7

20

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 :)

Sign up to request clarification or add additional context in comments.

2 Comments

No, unfortunately it does break. I do re-throw, but I would expect the application to only break further up the call stack?
Remember to rethrow the right way :) stackoverflow.com/questions/178456/…
5

I had a similar problem where a thrown exception wasn't being caught. In my case it was because I had the error being thrown in an async function that didn't return a Task.

Incorrect Implementation

async void myThrowFunction () {
  await something()
  throw new Exception('foo')
}

Correct Implementation

async Task myThrowFunction () {
  await something()
  throw new Exception('foo')
}

1 Comment

I had something similar. Only the function had no async / await and was just returing a task retrieved from another function. This was wrapped in an try/catch, but offcourse the returning of the task is happening before the task is executed in that case.
4

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

Comments

4

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.

Comments

0

This one was pretty interesting... I had a piece of code like this:

var pdfDoc = new PdfLoadedDocument(stream, true); // open each stream with repair = true

try
{
    PdfDocumentBase.Merge(finalDoc, options, pdfDoc);
}
catch(Exception e)
{
    var i = 10;
}

I was expecting the exception to be thrown from PdfDocuemtnBase.Merge method but that wasn't true. :D

I then enabled Common Language Runtime Exceptions option in Visual Studio's Exception Settings:

Visual Studio's Exception Settings window

Re-ran the code and guess what!?

The exception was being thrown by the line immediately above which was outside the try {} block:

var pdfDoc = new PdfLoadedDocument(stream, true); // open each stream with repair = true

Lesson learned: not make assumptions trying to guess where the exception is\should be thrown.

Comments

-2

I've also had such an issue and it was driving me nuts for quite some time, but in the end I figured it out. It's quite stupid, but maybe it might help someone:

public IActionResult SomeFunction()
{
    try
    {
        return Json(new ClassWhichTakes2Parameters("FirstParameter"), "SecondParameter"); //comma placed in the wrong spot
    }
    catch (Exception ex)
    {
        //some code
    }
}

It should have looked like:

public IActionResult SomeFunction()
{
    try
    {
        return Json(new ClassWhichTakes2Parameters("FirstParameter", "SecondParameter"));
    }
    catch (Exception ex)
    {
        //some code
    }
}

Since I had many return statements in that function I didn't catch this right away.

Also, the error message I've been receiving wasn't quite what I have expected at first, but now it makes sense:

System.InvalidOperationException: Property 'JsonResult.SerializerSettings' must be an instance of type 'Newtonsoft.Json.JsonSerializerSettings'.

Comments

-7

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.

3 Comments

This is a stylistic thing, there is nothing inherently wrong with returning in a catch block, or having multiple returns (it can even make code simpler by having multiple break points). This is not an answer to the question anyway (I know, I'm very late)
You have actually written this with a syntax error. You are redeclaring leadID inside the try block.
Well, having multiple return statements is much better than having an obvious syntax error. (Although there is nothing wrong with any of them.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.