什么是内部异常 [英] What is inner Exception

查看:471
本文介绍了什么是内部异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



如果我错了,请更正我


当前异常将使用innerexception。


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



我是这样吗?

解决方案

您可以看到下面的代码。



第一步,我将abc解析为整数。它会引发FormatException。



在catch块中,我尝试打开文本文件来记录异常消息。但是这个文件不存在。 FileNotFoundException将被提升。



我想知道什么引发了第二个异常,所以我将第一个异常(或FormatException)添加到第二个异常的构造函数。 >

现在第一个异常是第二个异常的InnerException。



在catch块中,我可以访问InnerException属性来了解什么是第一个例外。



有用吗?

  using System; 
使用System.IO;
public class Program
{
public static void Main()
{
try
{
try
{
var num = int.Parse(abc);
}
catch(异常内部)
{
try
{
var openLog = File.Open(DoesNotExist,FileMode.Open);
}
catch
{
throw new FileNotFoundException(OutterException,inner);
}
}
}
catch(异常e)
{
string inMes,outMes;
if(e.InnerException!= null)
inMes = e.InnerException.Message;
outMes = e.Message;
}
}
}


I have read the MSDN but, I could not understand this concept.

Correct me if I am wrong,

A innerexception will be used in hand with current exception.

Inner exception will occur first and then the current exception will occur (if there is an exception) that is the reason why InnerException is checked against null. In order to retain inner exception we have to pass it as a parameter.

Am I right with this?

解决方案

You can see the code below.

First step, i parse "abc" to integer. It will raise FormatException.

In catch block, i try to open text file to log exception message. But this file didn't exist. FileNotFoundException will be raise.

I want to know what raise the second exception, so i add the first exception (or FormatException) to constructor of the second exception.

Now the first exception is InnerException of the second exception.

In catch block, i can access InnerException properties to know what is the first exception.

It's useful?

using System;
using System.IO;
public class Program
{
    public static void Main( )
    {
        try
        {
            try
            {
                var num = int.Parse("abc");                
            }
            catch ( Exception inner )
            {
                try
                {
                    var openLog = File.Open("DoesNotExist", FileMode.Open);
                }
                catch
                {
                    throw new FileNotFoundException("OutterException", inner);
                }                              
            }
        }
        catch ( Exception e)
        {
            string inMes, outMes;
            if (e.InnerException != null)
                inMes = e.InnerException.Message;
            outMes = e.Message;
        }        
    }
}

这篇关于什么是内部异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆