您现在的位置是:首页 >

500错误原因解决方法 处理异常和错误

火烧 2021-04-27 15:00:10 1044
处理异常和错误   if语句能检查错误 但必须在运行时 try/catch语句能在编译时检查异常   处理异常和错误 gt fi ally块的用途  当打开文件 操作发生错误 虽然捕捉到异常 但资源没

处理异常和错误  

  if语句能检查错误 但必须在运行时 try/catch语句能在编译时检查异常

  处理异常和错误>finally块的用途

  当打开文件 操作发生错误 虽然捕捉到异常 但资源没被释放 所以finally块可用来释放资源或其它

  代码

  using System;

  using System Collections Generic;

  using System Text;

  using System IO;

  namespace FinallyDemo

  {

  class Program

  {

  static void Main(string[] args)

  {

  const string filePath = @ C:FinallyDemo txt ;

  FileStream fs=null;

  try

500错误原因解决方法 处理异常和错误

  {

  Console WriteLine( 开始执行文件的比较操作 );

  fs = new FileStream(filePath FileMode CreateNew FileAccess ReadWrite);

  byte[] bytes = Encoding Default GetBytes( 这是一个字符串 将插入到文本文件 );

  //向流中写入指定的字节数组

  fs Write(bytes bytes Length);

  //将缓冲区的内容存储到媒介并清除缓冲区

  fs Flush();

  //将流指针移到开头

  fs Seek( SeekOrigin Begin);

  byte[] bytes = new byte[bytes Length];

  //从

  fs Read(bytes bytes Length);

  string str = Encoding Default GetString(bytes );

  Console WriteLine( 从文件中读出的字符串为 + Environment NewLine+str);

  }

  catch (IOException ex)

  {

  Console WriteLine( 发生了文件处理的错误! + ex Message);

  }

  finally

  {

  Console WriteLine( 不论是否发生异常 都会执行finally到这里 );

  if (fs != null)

  {

  fs Close();

  }

  Console ReadLine();

  }

  }

  }

lishixinzhi/Article/program/net/201311/11798  
永远跟党走
  • 如果你觉得本站很棒,可以通过扫码支付打赏哦!

    • 微信收款码
    • 支付宝收款码