user3163495
user3163495

Reputation: 3557

C# Exception - make the "Source Error" the line where the method was called

In C#, if I call a canned method (like Regex.Replace) and it throws an exception, the error message marks the line where the method was called, like this:

Method Call:

//
//
string str = Regex.Replace("Hello", null, "");
//
//

enter image description here

However, if I write my own method (like MyRegex.MyReplace) and it throws an exception, the error message marks the line where the exception was thrown:

public static class MyRegex
{
    public static string MyReplace(string input, string pattern, string replacement)
    {
        if (pattern == null)
        {
            throw new Exception("Pattern must not be null.");
        }
        else
        {
            return Regex.Replace(input, pattern, replacement);
        }
    }
}

Method Call:

//
//
string str = MyRegex.MyReplace("Hello", null, "");
//
//

enter image description here

How can I throw an Exception within a method, and have the error message mark where the method was called (like canned methods), instead of where the exception was thrown?

Upvotes: 2

Views: 399

Answers (1)

Gabriel Luci
Gabriel Luci

Reputation: 40928

The line shown is the lowest point in the call stack where the source code is available.

You can't see any of the code inside Regex.Replace, so it only shows you the line in your code where you called it.

But because throw new Exception() is your code, that's what it shows.

If you built a DLL and used that in another project (and did not copy the .pdb file) then it would behave the same way as your Regex.Replace example, since the new project can't see the source code inside the DLL.

But if you copy over the .pdb file and run the new project on the same computer where the source code of the DLL is, then Visual Studio does know where to find the source code, and it will still show you the exception in your DLL code. (at least, I know Visual Studio will behave that way - I'm not sure if ASP.NET would display that to the browser)

Upvotes: 2

Related Questions