问题
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:
- when you want to handle the exception.
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