控制台中的 Try-Catch-Finally c#

Try-Catch-Finally c# in Console

我需要写一个 Try-Catch-Finally。 首先,我是编程新手。 回到问题。

我想在 Try-Block 中打开一个不存在的文本。

在 Catch-Block 中,消息框应该显示 FileNotFoundException。

我仍然不知道我应该在 Finally-Block 中放什么。

try
{
   FileStream File = new FileStream("beispiel.txt", FileMode.Open);
}
catch (FileNotFoundException fnfex)
{
   //MessageBox with fnfex
}
finally
{
   //idk
}

谢谢

最后是始终执行的代码。我会说使用 finally 块来清理任何可能存在的东西是一种常见的模式。例如,如果您有文件流...

如果类型不正确,请原谅,我目前没有 C#,但模式仍然存在...

FileStream file;

try {
    file = new FileStream("example.txt", FileMode.Open);
    file.open();
}
catch (Exception ex) {
    //message box here
}
finally {
    // Clean up stuff !
    if (file != null) {
        file.close()
    }
}

catchfinally的共同用法是在try[=26=中获取和使用资源]块,在catch块处理异常,在finally块释放资源。有关更多信息,请查看 https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/try-catch-finally

因为你只是想捕获异常然后打印出一条消息,你可以简单地去掉 finally 块,像这样:

try
{
   using (FileStream File = new FileStream("beispiel.txt", FileMode.Open)){}
}
catch (FileNotFoundException fnfex)
{
   //MessageBox with fnfex
   MessageBox.Show(fnfex.Message);
}

using 语句确保对象一超出范围就被释放,它不需要显式代码或 finally 以确保发生这种情况。

Finally 用于有保证的做某事的方式,即使抛出异常也是如此。在你的情况下,你可以处理你的流,但通常最好对实现 IDisposable 的对象使用 using 语句,所以你可以只做

using (var stream = new FileStream(...))
{
   // do what ever, and the stream gets automatically disposed.
}

参见:

using statement

IDisposable

DialogResult result;

try
{
    FileStream File = new FileStream("beispiel.txt", FileMode.Open);
}
catch (FileNotFoundException fnfex)
{
    result =
        MessageBox.Show(
            this, 

            // Message: show the exception message in the MessageBox
            fnfex.Message, 

            // Caption
            "FileNotFoundException caught", 

            // Buttons
            MessageBoxButtons.OK,
            MessageBoxIcon.Question, 
            MessageBoxDefaultButton.Button1, 
            MessageBoxOptions.RightAlign);
}
finally
{
    // You don't actually NEED a finally block

}

除了人们已经说过的 try...catch...finally 块之外,我相信您正在寻找的是

try {
    file = new FileStream("example.txt", FileMode.Open);
    file.open();
}
catch (Exception ex) {
    MessageBox.Show(ex.Message);
}

但是你需要在你的项目中添加对System.Windows.Forms的引用,并在你的class

中添加using语句
using System.Windows.Forms;

或者,如果您只想在控制台中显示消息,您可以使用

Console.WriteLine(e.Message);

忘记引用