سؤال

I have this code:

private void btnNext_Click(object sender, RoutedEventArgs e){
  try
      {
         // Lots of codes in here
      }

  catch (Exception ex)
      {
        System.Windows.MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace.ToString()) 
      }
  finally
      {}
}

It is catching an exception but not telling me where the exception is occurring inside the code. The only thing I'm getting is this.

   Object reference not set to an instance of an object
   at ProjectPath.btnNext_Click(Object sender, RoutedEventArgs e)

The release code works fine on a lot a machines, but on few machines, it throws this exception. I just can't figure out where on the code the exception is occurring while running on those machines. Is there a way to find the exact line where the exception is occurring? ex.StackTrace didn't get the job done.

Any help will be appreciated.

هل كانت مفيدة؟

المحلول

You should ideally put separate try-catch blocks around areas where you think an exception would be thrown - instead of putting everything in the same one.

Otherwise, when you debug, it creates pdb files which - if they're present in the folder where the file is executing, you can get the line number.

That said, this error is pretty common, you have a null somewhere.

Added: Over here I'm assuming that for some reason you can't get the debugger to stop on exception, and/or can't trace it because you're deploying it to a third party or something.

نصائح أخرى

To find the exact location -- the specific line in your source code -- it helps if you run the code in a debugger and set a breakpoint within the exception handler.

If you examine the data structure referenced as a parameter to the exception handler (ex in the example), you will find a data member named StackTrace. If the location is anywhere, it will be in here. Here, for example, is a string for an exception that I am working on right how:

at DOffice.BrMan.getLastReportRefreshed() in E:\\src\\BrMan.cs:line 5370
at DOffice.BrParms.lookupParmByParmName(String parmName) in E:\\src\\BrParms.cs:line 169
at DOffice.BrMan.populateAllFromTextFile(String workDirectory) in E:\\src\\BrMan.cs:line 3218
at DOffice.BrMan.setWorkPath(String pathOfCurrentDoc) in E:\\src\\BrMan.cs:line   1686
at DOffice.Form_Dash.InitWork(Object sender) in E:\\src\\Form_Dash.cs:line 1261
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top