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

好久不见. 提交于 2019-11-30 12:48:07

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.

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

You should replace

throw ex;

by

throw;

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 .

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

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