处理异常和错误>

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
            {
                Console.WriteLine(
"开始执行文件的比较操作");
                fs 
= new FileStream(filePath, FileMode.CreateNew, FileAccess.ReadWrite);
                
byte[] bytes = Encoding.Default.GetBytes("这是一个字符串,将插入到文本文件");
                
//向流中写入指定的字节数组
                fs.Write(bytes,0,bytes.Length);
                
//将缓冲区的内容存储到媒介并清除缓冲区。
                fs.Flush();
                
//将流指针移到开头。
                fs.Seek(0, SeekOrigin.Begin);
                
byte[] bytes2 = new byte[bytes.Length];
                
//
                fs.Read(bytes2, 0, bytes.Length);
                
string str = Encoding.Default.GetString(bytes2);
                Console.WriteLine(
"从文件中读出的字符串为" + Environment.NewLine+str);
            }
            
catch (IOException ex)                
            {
                Console.WriteLine(
"发生了文件处理的错误!" + ex.Message);
            }
            
finally
            {
                Console.WriteLine(
"不论是否发生异常,都会执行finally到这里");
                
if (fs != null)
                {
                    fs.Close();
                }
                Console.ReadLine();
            }
        }
    }
}

相关文章: