Skip to main content
 首页 » 编程设计

c#之对象引用的自定义消息未设置为对象的实例

2024年02月23日18xing901022

你好
我们有一个巨大的 Windows 应用程序,异常处理很差。应用程序从很多地方抛出对象引用错误,系统错误消息显示给用户,因为它正在使用消息框。

我正在寻找一个简单的解决方案,可用于将此消息替换为对整个应用程序用户友好的内容

谢谢...

请您参考如下方法:

@Anz:在代码中的每个地方都使用异常处理是不好的,所以请始终牢记这一点,并且您必须知道所有不同类型的异常的含义是什么。 在你的场景中,你得到了“对象引用异常”,这个异常的主要原因是你在访问变量时没有检查 null

Exa_1:-

数据集 ds;

现在如果我以 ds.Table.count() 的形式访问它,它会给出异常,所以我们应该在这里使用

数据集 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);

如果你想在异常句柄中显示自定义消息,那么你可以创建自己的异常类,它将覆盖异常类,然后你可以像这样抛出和捕获:

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

在你使用 try catch use 的代码中

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