Ricardo Alves
Ricardo Alves

Reputation: 1121

C# throw exception to caller

I have a function that needs to throw an exception, but I wanted it to throw that exception to the line where I called that function:

static int retrieveInt()
{
    int a = getInt();
    if(a == -1)
        throw new Exception("Number not found"); //The runtime error is pointing to this line
    return a;
}

static void Main(string[] args)
{
     int a = retrieveInt(); //The runtime error would be happening here
}

Upvotes: 1

Views: 4173

Answers (3)

Ricardo Alves
Ricardo Alves

Reputation: 1121

After 2 hours searching I found the answer to my question. To do what I wanted it is needed to user [System.Diagnostics.DebuggerStepThrough] before the function:

[System.Diagnostics.DebuggerStepThrough]
static int retrieveInt()
{
    int a = getInt();
    if(a == -1)
        throw new Exception("Number not found"); //The runtime error will not be here
    return a;
}

static void Main(string[] args)
{
     int a = retrieveInt(); //The runtime error happens now here
}

Upvotes: 6

Justin
Justin

Reputation: 424

How about this ?

public static int NewInt
{
    get
    {
            throw new Exception("Number not found");
    }
}

static void Main(string[] args)
{
    int a = NewInt;
}

Upvotes: -1

David
David

Reputation: 10708

The described behaviour is not strictly possible, but working around to the desired effect is.

The issue you're running into is that in Visual Studio, execution pauses and we see exceptions from the most available location with debug info. For framework methods, this means the method call, even though the exception is being thrown a couple of calls deeper. Since the exception is coming from the same project you're debugging, you'll always have debug info for the actual throw line, and thus you'll always reach that line.

The workaround here is to utilize the Call Stack window in VS, which will include a couple lines down the method call which triggered the error, and double-clicking on this will bring you where you want to be, including all local variables at the time of the call. This is analogous to the framework exception behaviour, because if you look at the stack trace, several frames are marked as "external" because they don't have debug info.

EDIT: To add some info about the behaviour of try and catch, catch will respond to any exception not already caught - thus, even if the exception is thrown several calls deeper, if it's not handled by the time the call stack unwinds into your try block, it'll hit the appropriate catch block (if there is one).

Upvotes: 2

Related Questions