Throw exception from Called function to the Caller Function's Catch Block

给你一囗甜甜゛ 提交于 2019-11-29 18:55:59

问题


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)
    {
        ...
    }
}

Here in the above code sample, I have two functions ReadFile and ReadCSVFile.
In the ReadCSVFile, I get an exception of type FileNotFoundExceptioon, 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?


回答1:


You have to use throw; instead of throw ex;:

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

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
    {
        ...
    }
}

Implement the catch block only:

  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) { throw new MessageException("Message", exc); }

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




回答2:


Just use throw in the called function. Dont overload catch blocks with multiple exception types. Let the caller take care of that.




回答3:


You should replace

throw ex;

by

throw;



回答4:


In the called function just use throw like this

 try
 {
   //you code
 }
 catch
 {
     throw;
}

Now, if the exception arise here then this will be caught by the caller function .




回答5:


Your code works fine here, Check here http://ideone.com/jOlYQ



来源:https://stackoverflow.com/questions/7024252/throw-exception-from-called-function-to-the-caller-functions-catch-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!