简体   繁体   中英

Custom message for Object reference not set to an instance of an object

Hi
We have a huge windows application with poor exception handling. The application throw object reference error from lot of places and the system error message is showing to users as it is using message boxes.

I am looking for a simple solution which can be used to replace this message to something user friendly for the entire application

Thanks...

@Anz: Its not good to use Exception handling in every where in code so always keep this in mind and you must know what is the meaning of all different type of Exception. In your scenario you are getting "object reference Exception" and the main reason of this exception is that you are not checking null while accessing variable like

Exa_1:-

DataSet ds;

now if i acces it as ds.Table.count() it will give Exception, so here we should use

DataSet ds;

 If(ds!=null)
 {
   int val = ds.Table.count();
 } 

Exa_2:-

     string strVariable=txtInput.Text;

     int number = Convert.Int32(strVariable); // here if txtInput.Text is empty them     it will through exception so here we can use

if(!String.IsNullOrEmpty(strVariable)) int number = Convert.Int32(strVariable);

And if you want to show custom Message in Exception handle then you can create your own Exception Class which will override Exception class then you can throw and catch like:

public class MyException : Exception
{
    public string customMessage;
    public MyException(string sourceName)
    {
        customMessage = sourceName + " can not be null";
    }
    public MyException()
    {
        customMessage="ObjectReferenceException";
    }        
}

And in code where you are usng try catch use

        try
        {

            throw new MyException("check");
        }
        catch (MyException ex)
        {
            MessageBox.Show(ex.customMessage);
        }

When you catch the exception and display the message box you just need to write a friendly message into the message box. I don't think displaying exception messages is a good idea - It could give away information about the structure of your application that a malicious user could use to attack the application.

** Additional **

Either way it is a big change. You either override the exception in lots of places, or override the display of the error message in lots of places. May I suggest that you consolidate the display of the error message in to one place so when you need new error messages you have one place to go, and therefore in future, one place to change if you need to change it.

In a WinForms application, you could use something like the technique described here for displaying a user-friendly error message.

That said, since the only reason for null reference exception is developer error, there is a strong code smell that the app has lots of overall problems. I would recommend at least to put in a logger in the exception handler that you're going to put in place, so that the errors will not go unnoticed.

You need to catch exception thrown by legacy application and log that exception in some log file and display appropriate user friendly message according to exception occured.

For example, instead of showing FileNotFound exception message along with stacktrace, you can just show "Application unable to find the file xyz".

use Application_Error event in global.asax if it is Asp.Net application

 Application_Error

 {
   HttpContext context = HttpContext.Current;

   Exception ex = context.Server.GetLastError();
  //process your exception

    if ( context.IsCustomErrorEnabled )
   {
      context.Server.ClearError();
      context.Server.Transfer( "~/error.aspx" );
   }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM