我有以下代碼。異常處理?
using System;
using System.IO;
class ExceptionHandling
{
public static void Main()
{
StreamReader streamReader = null;
try
{
streamReader = new StreamReader("C:\\Sample Files\\Data.txt");
Console.WriteLine(streamReader.ReadToEnd());
}
catch(FileNotFoundException ex)
{
Console.WriteLine("Please check if the file {0} exists",ex.FileName);
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
if (streamReader !=null)
{
streamReader.Close();
}
Console.WriteLine("FInally Block");
}
}
}
我的問題如下:
1)StreamReader streamReader = null;
爲什麼StreamReader的分配爲空?
2)streamReader = new StreamReader
我只是想澄清一下。 StreamReader引用變量是否指向StreamReader對象?
3)如果streamReader = new StreamReader("C:\\Sample Files\\Data.txt");
發生異常,streamReader是否仍然打開?
4)既然我們寫了StreamReader streamReader = null;
不是streamReader總是爲null,因此在Finally塊中不可能關閉嗎?
5)我不知道FileNotFoundException ex
和Exception ex
是如何工作的。是不是ex對象引用變量,並且只有當我們將它們分配給諸如Exception ex = new Exception
之類的對象時,它纔會起作用?
問題太多。閱讀文檔和C#圖書的良好開端是您應該開始的地方。 –