Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why exception is thrown on caller instead of on problematic line

I have a simple program:

class Program
{   
    static void Main(string[] args)
    {
        Run().Wait();
    }

    private static async Task Run()
    {
        string someVariable = null;
        someVariable.Replace(",", ".");
    }
}

Run() method is intentionally designed to throw NullReferenceException. What bothers me is why exception is thrown on the line

Run.Wait()

instead of on

someVariable.Replace(",",".");

The actuall exception is available in InnerException - why is that? I lose debugging context, because exception is thrown outside of Run method. enter image description here

If my program is synchronous:

class Program
{
    static void Main(string[] args)
    {
        Run();
    }

    private static void Run()
    {
        string someVariable = null;
        someVariable.Replace(",", ".");
    }
}

exception is thrown on the correct line. Why async breaks this?

like image 917
Loreno Avatar asked Nov 17 '25 19:11

Loreno


1 Answers

When you call Run.Wait(), the Run() method has thrown a null exception then Wait method will throw AggregateException. Btw you don't loss your context. If you click on [View Details] and view the StackTrace of InnerException of the current exception, you can found that the exception came from Run() method:

enter image description here

like image 71
Nhan Phan Avatar answered Nov 19 '25 10:11

Nhan Phan