当前位置: 移动技术网 > IT编程>开发语言>c# > C#异常处理中try和catch语句及finally语句的用法示例

C#异常处理中try和catch语句及finally语句的用法示例

2019年07月18日  | 移动技术网IT编程  | 我要评论

使用 try/catch 处理异常
try-catch 块的用途是捕捉和处理工作代码所生成的异常。 有些异常可以在 catch 块中处理,解决问题后不会再次引发异常;但更多情况下,您唯一能做的是确保引发适当的异常。
示例
在此示例中,indexoutofrangeexception 不是最适当的异常:对本方法而言 argumentoutofrangeexception 更恰当些,因为错误是由调用方传入的 index 参数导致的。

class testtrycatch
{
  static int getint(int[] array, int index)
  {
    try
    {
      return array[index];
    }
    catch (system.indexoutofrangeexception e) // cs0168
    {
      system.console.writeline(e.message);
      // set indexoutofrangeexception to the new exception's innerexception.
      throw new system.argumentoutofrangeexception("index parameter is out of range.", e);
    }
  }
}


注释
导致异常的代码被括在 try 块中。 在其后面紧接着添加一个 catch 语句,以便在 indexoutofrangeexception 发生时对其进行处理。 catch 块处理 indexoutofrangeexception,并引发更适当的 argumentoutofrangeexception 异常。 为给调用方提供尽可能多的信息,应考虑将原始异常指定为新异常的 innerexception。 因为 innerexception 属性是只读,所以必须在新异常的构造函数中为其赋值。


使用 finally 执行清理代码
finally 语句的目的是确保即使在引发异常的情况下也能立即进行必要的对象(通常是保存外部资源的对象)清理。此类清理功能的一个示例是在使用后立即对 filestream 调用 close,而不是等待公共语言运行时对该对象进行垃圾回收,如下所示:

static void codewithoutcleanup()
{
  system.io.filestream file = null;
  system.io.fileinfo fileinfo = new system.io.fileinfo("c:\\file.txt");

  file = fileinfo.openwrite();
  file.writebyte(0xf);

  file.close();
}

为了将上面的代码转换为 try-catch-finally 语句,需要将清理代码与工作代码分开,如下所示。

static void codewithcleanup()
{
  system.io.filestream file = null;
  system.io.fileinfo fileinfo = null;

  try
  {
    fileinfo = new system.io.fileinfo("c:\\file.txt");

    file = fileinfo.openwrite();
    file.writebyte(0xf);
  }
  catch(system.unauthorizedaccessexception e)
  {
    system.console.writeline(e.message);
  }
  finally
  {
    if (file != null)
    {
      file.close();
    }
  }
}

因为在 openwrite() 调用前,try 块内随时都有可能发生异常,openwrite() 调用本身也有可能失败,所以我们无法保证该文件在我们尝试关闭它时处于打开状态。 finally 块添加了一项检查,以确保在调用 close 方法前,filestream 对象不为 null。如果没有 null 检查,finally 块可能引发自身的 nullreferenceexception,但是应当尽可能避免在 finally 块中引发异常。
在 finally 块中关闭数据库连接是另一个不错的选择。因为有时候数据库服务器允许的连接数是有限的,所以应尽快关闭数据库连接。在由于引发了异常而无法关闭连接的情况下,使用 finally 块也是比等待垃圾回收更好的一种选择。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网