Skip to main content
 首页 » 编程设计

c#之无法生成异常 : very simple C# Windows Form Application and app. 配置

2024年02月23日24mq0036

我是 C# (VS 2010) 的新手,我想了解如何处理异常。 除了我编写的非常简单的程序,我无法生成一个。

这是 C# 代码:

        private void button1_Click(object sender, EventArgs e) 
        { 
            String messageOut = System.Configuration.ConfigurationSettings.AppSettings["tester"]; 
            MessageBox.Show(messageOut); 
        } 

这是我作为测试创建的 app.config

<?xml version="1.0" encoding="utf-8" ?> 
<configuration> 
  <appSettings> 
    <add key="buttonText" value="message from ray"/> 
  </appSettings> 
</configuration> 

如您所见,app.config 中没有“tester”键,我本以为会出现异常。然而,我只是收到一个空白的消息框。

更新:

感谢您的回答,Hawxby。 我想第 2 部分对我来说是理解 try and catch。 这在这里行得通吗?

   MessageBox.Show(System.Configuration.ConfigurationSettings.AppSettings["text"].ToString()); 
 
   try 
   { 
      String tester = System.Configuration.ConfigurationSettings.AppSettings["text"].ToString(); 
      tester = null; 
 
   } 
   catch 
   { 
       MessageBox.Show("Missing key!"); 
   } 

请您参考如下方法:

如果您请求一个不存在的配置项,它会返回一个空字符串。例如,如果您尝试在您的 messageOut 变量上调用 .ToString(),那将导致一个,因为您不能在空对象。

如果您只是想让您的应用程序抛出异常

throw new Exception("Something broke");