将异常从被调用函数抛出到调用者函数的Catch块 [英] Throw exception from Called function to the Caller Function's Catch Block

查看:379
本文介绍了将异常从被调用函数抛出到调用者函数的Catch块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

internal static string ReadCSVFile(string filePath)
{
    try
    {
        ...
        ...
    }
    catch(FileNotFoundException ex)
    {
        throw ex;
    }
    catch(Exception ex)
    {
        throw ex;
    }
    finally
    {
        ...
    }
}


//Reading File Contents

public void ReadFile()
{
    try
    {
        ...
        ReadCSVFile(filePath);
        ...
    }
    catch(FileNotFoundException ex)
    {
        ...
    }
    catch(Exception ex)
    {
        ...
    }
}

在上面的代码示例中,我有两个函数 ReadFile ReadCSVFile

ReadCSVFile ,我收到FileNotFoundException类型的异常,该异常被捕获在catch(FileNotFoundException)块中。但是,当我将此异常扔到 ReadFile 函数的catch(FileNotFoundException)中时,它被捕获在catch(Exception)块中,而不是catch(FileNotFoundException)。此外,在调试时,ex的值表示为对象未初始化。如何在不丢失内部异常或异常消息最少的情况下,将异常从被调用函数扔到调用者函数的catch块?

Here in the above code sample, I have two functions ReadFile and ReadCSVFile.
In the ReadCSVFile, I get an exception of type FileNotFoundException, which gets caught in the catch(FileNotFoundException) block. But when I throw this exception to be caught in the catch(FileNotFoundException) of the ReadFile Function, it gets caught in the catch(Exception) block rather than catch(FileNotFoundException). Moreover, while debugging, the value of the ex says as Object Not Initialized. How can I throw the exception from the called function to the caller function's catch block without losing the inner exception or atleast the exception message?

推荐答案

您必须使用 throw; 而不是 throw ex;

internal static string ReadCSVFile(string filePath)
{
    try
    {
        ...
        ...
    }
    catch(FileNotFoundException ex)
    {
        throw;
    }
    catch(Exception ex)
    {
        throw;
    }
    finally
    {
        ...
    }
}

除此之外,如果您在catch块中什么也没做,只是重新抛出,则根本不需要catch块:

Besides that, if you do nothing in your catch block but rethrowing, you don't need the catch block at all:

internal static string ReadCSVFile(string filePath)
{
    try
    {
        ...
        ...
    }
    finally
    {
        ...
    }
}

仅执行catch块:


  1. 当您要处理异常时。

  2. 当您想通过将新捕获的异常作为内部异常抛出新异常来向异常添加其他信息时:

  1. when you want to handle the exception.
  2. when you want to add additional information to the exception by throwing a new exception with the caught one as inner exception:

catch(Exception exc){抛出新的MessageException( Message,exc); }

您不必在每个方法中都实现catch块,除非有异常可以冒出来。

You do not have to implement a catch block in every method where an exception can bubble through.

这篇关于将异常从被调用函数抛出到调用者函数的Catch块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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