开发者

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

internal static string ReadCSVFile(string filePat开发者_开发问答h)
{
    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 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?


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜