gpt4 book ai didi

c# - 什么是内部异常

转载 作者:IT王子 更新时间:2023-10-29 04:33:30 25 4
gpt4 key购买 nike

我已经阅读了 MSDN,但是我无法理解这个概念。

如果我错了,请纠正我,

A innerexception will be used in hand with current exception.

内部异常会先发生,然后才会发生当前异常(如果有异常),这就是为什么 InnerException 会根据 null 检查的原因。为了保留内部异常,我们必须将其作为参数传递。

我说的对吗?

最佳答案

你可以看到下面的代码。

第一步,我将 "abc" 解析为 int .它会提高 FormatException .

在第一个 catch block (处理引发的 FormatException),我尝试打开一个文本文件来记录异常消息。但是这个文件不存在,所以引发了第二个异常,这次是 FileNotFoundException 类型.

我想存储引发第二个异常的原因,因此我将第一个异常(FormatException 类型的fe)添加到 fe 参数(FormatException 类型)传入 FileNotFoundException(String, Exception)第二个异常的构造函数。

该构造函数会将第一个异常存储在 InnerException 中第二个异常的属性。

在最外面的 catch block 中,我可以访问 InnerException 的属性以了解第一个异常是什么。

有用吗?

using System;
using System.IO;

public class Program
{
public static void Main( )
{
try
{
try
{
var num = int.Parse("abc"); // Throws FormatException
}
catch ( FormatException fe )
{
try
{
var openLog = File.Open("DoesNotExist", FileMode.Open);
}
catch
{
throw new FileNotFoundException("NestedExceptionMessage: File `DoesNotExist` not found.", fe );
}
}
}
// Consider what exception is thrown: FormatException or FileNotFoundException?
catch ( FormatException fe )
{
// FormatException isn't caught because it's stored "inside" the FileNotFoundException
}
catch ( FileNotFoundException fnfe )
{
string innerMessage = "", outerMesage;
if (fnfe.InnerException != null)
innerMessage = fnfe.InnerException.Message; // Inner exception (FormatException) message
outerMesage = fnfe.Message;
Console.WriteLine($"Inner Exception:\n\t{innerMessage}");
Console.WriteLine($"Outer Exception:\n\t{outerMesage}");
}
}
}

控制台输出

Inner Exception:
Input string was not in a correct format.
Outer Exception:
NestedExceptionMessage: File `DoesNotExist` not found.

内部异常指的是最终抛出的更深层次的嵌套异常。 外部 异常指的是最浅(范围内)异常。

关于c# - 什么是内部异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22826067/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com