欢迎注册会员!在线投稿,发布笑话,分享快乐!
返回首页您现在的位置: 主页 > 时事杂谈 > 文章内容

杂谈异常处理try

作者: 幽默笑话网 来源: www.ymxhw.com 时间: 2014-01-11 阅读: 在线投稿

杂谈异常处理try-catch-finally

1.   前言

最近这段时间正开发一个店铺管理系统,这个项目定位于给中小型店铺使用的软件系统。简单的说,它处理商品的进货,销售,退货等功能。软件虽小,五脏俱全,里面涉及的技术跟大型应用软件其实差别也不大,其中有加密、数据访问、异常处理、日志、验证、ORM、依赖注入等。

本篇文章主要介绍C#语言的异常处理方面的内容,其中包含的主要内容:

 

2.   异常概述

 

3.   异常处理基础知识 3.1.  如何:使用 Try/Catch 块捕捉异常

将可能引发异常的代码节放在 Try 块中,而将处理异常的代码放在 Catch 块中。Catch 块是一系列以关键字 catch 开头的语句,语句后跟异常类型和要执行的操作。

下面的代码示例使用 Try/Catch 块捕捉可能的异常。Main 方法包含带有 StreamReader 语句的 Try 块,该语句打开名为 data.txt 的数据文件并从该文件写入字符串。Try 块后面是 Catch 块,该块捕捉 Try 块产生的任何异常。

 

using System;

using System.IO;

using System.Security.Permissions;

// Security permission request.

[assembly:FileIOPermissionAttribute(SecurityAction.RequestMinimum, All = @"c:\data.txt")]

public class ProcessFile {

    public static void Main() {

        try {

            StreamReader sr = File.OpenText("data.txt");

            Console.WriteLine("The first line of this file is {0}", sr.ReadLine());   

        }

        catch(Exception e) {

            Console.WriteLine("An error occurred: '{0}'", e);

        }

    }

}

 

3.2.  如何:在 Catch 块中使用特定异常

发生异常时,异常沿堆栈向上传递,每个 Catch 块都有机会处理它。Catch 语句的顺序很重要。将针对特定异常的 Catch 块放在常规异常 Catch 块的前面,否则编译器可能会发出错误。确定正确 Catch 块的方法是将异常的类型与 Catch 块中指定的异常名称进行匹配。如果没有特定的 Catch 块,则由可能存在的常规 Catch 块捕捉异常。

 

下面的代码示例使用 try/catch 块捕获 InvalidCastException。该示例创建一个名为 Employee 的类,它带有一个属性:职员级别 (Emlevel)。PromoteEmployee 方法取得对象并增加职员级别。将 DateTime 实例传递给 PromoteEmployee 方法时,发生 InvalidCastException。

 

using System;

public class Employee

{

   //Create employee level property.

   public int Emlevel

   {

      get

         {

         return(emlevel);

         }

      set

         {

         emlevel = value;

         }

   }

   int emlevel;

}

public class Ex13

{

   public static void PromoteEmployee(Object emp)

   {

   //Cast object to Employee.

   Employee e = (Employee) emp;

   // Increment employee level.

   e.Emlevel = e.Emlevel + 1;

   }

 

   public static void Main()

   {

   try

      {

   Object o = new Employee();

   DateTime newyears = new DateTime(2001, 1, 1);

   //Promote the new employee.

   PromoteEmployee(o);

   //Promote DateTime; results in InvalidCastException as newyears is not an employee instance.

   PromoteEmployee(newyears);

      }

   catch (InvalidCastException e)

      {

      Console.WriteLine("Error passing data to PromoteEmployee method. " + e);

      }

   }

}

 

3.3.  如何:显式引发异常

可以使用 throw 语句显式引发异常。还可以使用 throw 语句再次引发捕获的异常。较好的编码做法是,向再次引发的异常添加信息以在调试时提供更多信息。

 

下面的代码示例使用 try/catch 块捕获可能的 FileNotFoundException。try 块后面是 catch 块,catch 块捕获 FileNotFoundException,如果找不到数据文件,则向控制台写入消息。下一条语句是 throw 语句,该语句引发新的 FileNotFoundException 并向该异常添加文本信息。

 

using System;

using System.IO;

 

public class ProcessFile

{

   public static void Main()

      {

      FileStream fs = null;

      try  

      {

         //Opens a text tile.

         fs = new FileStream(@"C:\temp\data.txt", FileMode.Open);

         StreamReader sr = new StreamReader(fs);

         string line;

 

         //A value is read from the file and output to the console.

         line = sr.ReadLine();

         Console.WriteLine(line);

      }

      catch(FileNotFoundException e)

      {

         Console.WriteLine("[Data File Missing] {0}", e);

         throw new FileNotFoundException(@"data.txt not in c:\temp directory]",e);

      }

      finally

      {

         if (fs != null)

            fs.Close();

      }

   }

}

 

3.4.  如何:使用 Finally 块
  • 上一篇:《魔兽杂谈》苍天哥林熊猫魔兽相声
  • 下一篇:Powered by phpwind
  • 相关阅读

    发表笑话