I have an application that assigns a list of values to a DataGridView.
This is done inside a Try catch block.
Occasionally there is an issue with the with the procedure that produces this list (also in a try catch block) and this causes an error when the assignment is done.
It appears the exception is never caught by the block doing the assignment and the application freezes.
Is the exception handled inside the assignment call so that it is not propagated out to the catch block?
The exception produced as a pop up states
"The following exception occurred in the DataGridView:
System.IndexOutOfrangeException: Index 1 does not have a value at
System.Windows.Forms.dataGridViewDataConnection.GetError(Int32 rowIndex)
To replace this default dialog please handle the DataError event"
The code is basically
public void SetupRunners(EventDetails _eventDetails)
{
try
{
RunnerAssociates.Clear();
RunnerAssociates = null;
RunnerAssociates = createRunnerAssociateList(selectedEventDetails);
runnerAssociatesDataGridView.DataSource = RunnerAssociates;
runnerAssociatesDataGridView.DataMember = string.Empty;
}
catch (Exception ex)
{
NZRB_Global.Utils.LogException(methodName, ex);
}
}
private List<Runner_Associate> createRunnerAssociateList(EventDetails _meetAndRace) //NZRB_Global.MeetAndRace _meetAndRace)
{
const string methodName = "createRunnerAssociateList";
List<Runner_Associate> lra = new List<Runner_Associate>();
try
{
if (null != _meetAndRace)
{
_meetAndRace.UpdateAllProfiles();
foreach (RunnerDetail rd in _meetAndRace.runners.runnerList)
{
Runner_Associate ra = new Runner_Associate();
ra.Number = rd.number;
ra.RunnerName = rd.name;
RunnerProfile profile = rd.GetRunnerProfile();
if ((rbJockeyDriver.Checked) || (rbCustom.Checked))
{
ra.AssociateName = rd.person;
}
else if (profile != null)
{
if (rbTrainers.Checked)
{
ra.AssociateName = profile.trainer;
}
else if (rbOwners.Checked)
{
ra.AssociateName = profile.owners;
}
}
lra.Add(ra);
}
}
}
catch (Exception ex)
{
NZRB_Global.Utils.LogException(methodName, ex);
}
return lra;
}
I'm getting unreachable code warning in catch block and I'm not able to debug. Please suggest me how to rectify that bug:
private void HandleDevelopmentServer()
{
string sErrMsg = "";
try
{
QuasarInterfaces.ISecurity oSecurity = null;
Global.CreateSecurityComponent(ref oSecurity);
System.Data.DataSet oDS;
DataTable dtDBSettings = new DataTable();
string sDBString = System.Configuration.ConfigurationSettings.AppSettings["Environment"];
Global.ReadDBConfig(sDBString, ref dtDBSettings);
oSecurity.FetchAllUsers(out oDS, out sErrMsg, dtDBSettings)
if (sErrMsg.Length > 0)
throw new Exception(sErrMsg);
if ((oDS != null) && (oDS.Tables.Count != 0))
{
DropDownList1.DataSource = oDS;
DropDownList1.DataBind();
}
}
catch (Exception e)
{
throw new Exception("HandleDevelopmentServer function failed;" + e.Message);
Global.writeLog("" + e.ToString());
}
}
This line will never happen:
Global.writeLog("" + e.ToString());
You are throwing an exception just above it, meaning this method will exit at that point to the previous in the call stack
By just switching the two it will be fine.
catch (Exception e)
{
Global.writeLog("" + e.ToString());
throw new Exception("HandleDevelopmentServer function failed;" + e.Message);
}
And you can also remove the "" +.
You have to switch the two lines in the catch block so that the log is written before the exception is thrown.
I'm deliberately throwing an exception for a particular scenario, but I would implicitly like to get the error message in string format. I'm aware that one of the overloads for the following exception is string message, but how do I access that string?
Here is the relevant snippet:
string errMsg;
private void Compress()
{
if (sourcePath.EndsWith(".zip"))
{
throw new FileLoadException
("File already compressed. Unzip the file and try again.");
errMsg = //I want the above string here
}
}
Do you mean this:?
try
{
throw new FileLoadException
("File already compressed. Unzip the file and try again.");
}
catch (Exception ex)
{
errMsg = ex.GetBaseException().Message;
}
You can't access the string THERE I'll explain a bit there:
string errMsg;
private void Compress()
{
if (sourcePath.EndsWith(".zip"))
{
throw new FileLoadException
("File already compressed. Unzip the file and try again.");
// The following line is unreachable as the throw ends the function and gets the exception to the calling function as there is no try catch block to catch the exception.
errMsg = //I want the above string here
}
}
A possibility would be to try/catch the exception in the method where you want to set the variable:
private void Compress()
{
if (sourcePath.EndsWith(".zip"))
{
try
{
throw new FileLoadException
("File already compressed. Unzip the file and try again.");
}
catch (Exception e)
{
errMsg = e.Message;
}
}
}
Or to catch the exception in the calling method instead:
try
{
Compress();
}
catch (Exception e)
{
}
regardless of method used the e.Message gives you the message of the exception as a string.
There is no point to try catch the exception and set the message. Unless you re-throw it
try
{
throw new FileLoadException("File already compressed. Unzip the file and try again.");
}
catch (Exception ex)
{
errMsg = ex.GetBaseException().Message;
throw;
}
I would rather do this
private void Compress()
{
if (sourcePath.EndsWith(".zip"))
{
errMsg = "File already compressed. Unzip the file and try again.";
return;
}
}
Not sure I 100% understand but if you want the message from that exception you can catch it and examine the Exception.Message
try
{
throw new FileLoadException("Custom error string");
}
catch (Exception exception)
{
Console.WriteLine(exception.Message);
}
here should be an solution for you :)
if (sourcePath.EndsWith(".zip"))
{
FileLoadException ex = new FileLoadException("File already compressed. Unzip the file and try again.");
errMsg = ex.ToString();
}
Console.WriteLine(errMsg);
To throw the exception that you made I would do soemthing like this
static string sourcePath = "test.zip"; //hardcoded file
static string errMsg; //the error string
private static void Compress()
{
try
{
if (!sourcePath.EndsWith(".zip"))
{
Console.WriteLine("File doesn't end with zip so it can be compressed"); //if it does not end with zip its rdy for compressing and here you can indput your code to compress
}
else
{
throw new Exception(); //instead of using try catch you can also generate the code in here instead of throwing an exception.
//when throwing a new exception you make it stop the if setting and jump into the catch if you use break it wont enter the catch but instead it will just jump over it.
}
}
catch
{
//Here it will generate the custom exception you wanted and put it inside the errMsg
errMsg = new FileLoadException("File already compressed. Unzip the file and try again.").ToString();
Console.WriteLine(errMsg);
}
ofc this is made in console that is why I use the console.writeline you can just change those out
If a finally block throws an exception, what exactly happens?
Specifically, what happens if the exception is thrown midway through a finally block. Do the rest of statements (after) in this block get invoked?
I am aware that exceptions will propagate upwards.
If a finally block throws an exception what exactly happens ?
That exception propagates out and up, and will (can) be handled at a higher level.
Your finally block will not be completed beyond the point where the exception is thrown.
If the finally block was executing during the handling of an earlier exception then that first exception is lost.
C# 4 Language Specification ยง 8.9.5: If the finally block throws another exception, processing of the current exception is terminated.
For questions like these I usually open up an empty console application project in Visual Studio and write a small sample program:
using System;
class Program
{
static void Main(string[] args)
{
try
{
try
{
throw new Exception("exception thrown from try block");
}
catch (Exception ex)
{
Console.WriteLine("Inner catch block handling {0}.", ex.Message);
throw;
}
finally
{
Console.WriteLine("Inner finally block");
throw new Exception("exception thrown from finally block");
Console.WriteLine("This line is never reached");
}
}
catch (Exception ex)
{
Console.WriteLine("Outer catch block handling {0}.", ex.Message);
}
finally
{
Console.WriteLine("Outer finally block");
}
}
}
When you run the program you will see the exact order in which catch and finally blocks are executed. Please note that code in the finally block after the exception is being thrown will not be executed (in fact, in this sample program Visual Studio will even warn you that it has detected unreachable code):
Inner catch block handling exception thrown from try block.
Inner finally block
Outer catch block handling exception thrown from finally block.
Outer finally block
Additional Remark
As Michael Damatov pointed out, an exception from the try block will be "eaten" if you don't handle it in an (inner) catch block. In fact, in the example above the re-thrown exception does not appear in the outer catch block. To make that even more clear look at the following slightly modified sample:
using System;
class Program
{
static void Main(string[] args)
{
try
{
try
{
throw new Exception("exception thrown from try block");
}
finally
{
Console.WriteLine("Inner finally block");
throw new Exception("exception thrown from finally block");
Console.WriteLine("This line is never reached");
}
}
catch (Exception ex)
{
Console.WriteLine("Outer catch block handling {0}.", ex.Message);
}
finally
{
Console.WriteLine("Outer finally block");
}
}
}
As you can see from the output the inner exception is "lost" (i.e. ignored):
Inner finally block
Outer catch block handling exception thrown from finally block.
Outer finally block
If there is an exception pending (when the try block has a finally but no catch), the new exception replaces that one.
If there is no exception pending, it works just as throwing an exception outside the finally block.
Quick (and rather obvious) snippet to save "original exception" (thrown in try block) and sacrifice "finally exception" (thrown in finally block), in case original one is more important for you:
try
{
throw new Exception("Original Exception");
}
finally
{
try
{
throw new Exception("Finally Exception");
}
catch
{ }
}
When code above is executed, "Original Exception" propagates up the call stack, and "Finally Exception" is lost.
The exception is propagated.
Throwing an exception while another exception is active will result in the first exception getting replaced by the second (later) exception.
Here is some code that illustrates what happens:
public static void Main(string[] args)
{
try
{
try
{
throw new Exception("first exception");
}
finally
{
//try
{
throw new Exception("second exception");
}
//catch (Exception)
{
//throw;
}
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
Run the code and you will see "second exception"
Uncomment the try and catch statements and you will see "first exception"
Also uncomment the throw; statement and you will see "second exception" again.
Some months ago i also faced something like this,
private void RaiseException(String errorMessage)
{
throw new Exception(errorMessage);
}
private void DoTaskForFinally()
{
RaiseException("Error for finally");
}
private void DoTaskForCatch()
{
RaiseException("Error for catch");
}
private void DoTaskForTry()
{
RaiseException("Error for try");
}
try
{
/*lacks the exception*/
DoTaskForTry();
}
catch (Exception exception)
{
/*lacks the exception*/
DoTaskForCatch();
}
finally
{
/*the result exception*/
DoTaskForFinally();
}
To solve such problem i made a utility class like
class ProcessHandler : Exception
{
private enum ProcessType
{
Try,
Catch,
Finally,
}
private Boolean _hasException;
private Boolean _hasTryException;
private Boolean _hasCatchException;
private Boolean _hasFinnallyException;
public Boolean HasException { get { return _hasException; } }
public Boolean HasTryException { get { return _hasTryException; } }
public Boolean HasCatchException { get { return _hasCatchException; } }
public Boolean HasFinnallyException { get { return _hasFinnallyException; } }
public Dictionary<String, Exception> Exceptions { get; private set; }
public readonly Action TryAction;
public readonly Action CatchAction;
public readonly Action FinallyAction;
public ProcessHandler(Action tryAction = null, Action catchAction = null, Action finallyAction = null)
{
TryAction = tryAction;
CatchAction = catchAction;
FinallyAction = finallyAction;
_hasException = false;
_hasTryException = false;
_hasCatchException = false;
_hasFinnallyException = false;
Exceptions = new Dictionary<string, Exception>();
}
private void Invoke(Action action, ref Boolean isError, ProcessType processType)
{
try
{
action.Invoke();
}
catch (Exception exception)
{
_hasException = true;
isError = true;
Exceptions.Add(processType.ToString(), exception);
}
}
private void InvokeTryAction()
{
if (TryAction == null)
{
return;
}
Invoke(TryAction, ref _hasTryException, ProcessType.Try);
}
private void InvokeCatchAction()
{
if (CatchAction == null)
{
return;
}
Invoke(TryAction, ref _hasCatchException, ProcessType.Catch);
}
private void InvokeFinallyAction()
{
if (FinallyAction == null)
{
return;
}
Invoke(TryAction, ref _hasFinnallyException, ProcessType.Finally);
}
public void InvokeActions()
{
InvokeTryAction();
if (HasTryException)
{
InvokeCatchAction();
}
InvokeFinallyAction();
if (HasException)
{
throw this;
}
}
}
And used like this
try
{
ProcessHandler handler = new ProcessHandler(DoTaskForTry, DoTaskForCatch, DoTaskForFinally);
handler.InvokeActions();
}
catch (Exception exception)
{
var processError = exception as ProcessHandler;
/*this exception contains all exceptions*/
throw new Exception("Error to Process Actions", exception);
}
but if you want to use paramaters and return types that's an other story
The exception propagates up, and should be handled at a higher level. If the exception is not handled at the higher level, the application crashes. The "finally" block execution stops at the point where the exception is thrown.
Irrespective of whether there is an exception or not "finally" block is guaranteed to execute.
If the "finally" block is being executed after an exception has occurred in the try block,
and if that exception is not handled
and if the finally block throws an exception
Then the original exception that occurred in the try block is lost.
public class Exception
{
public static void Main()
{
try
{
SomeMethod();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
public static void SomeMethod()
{
try
{
// This exception will be lost
throw new Exception("Exception in try block");
}
finally
{
throw new Exception("Exception in finally block");
}
}
}
Great article for Details
I had to do this for catching an error trying to close a stream that was never opened because of an exception.
errorMessage = string.Empty;
try
{
byte[] requestBytes = System.Text.Encoding.ASCII.GetBytes(xmlFileContent);
webRequest = WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "text/xml;charset=utf-8";
webRequest.ContentLength = requestBytes.Length;
//send the request
using (var sw = webRequest.GetRequestStream())
{
sw.Write(requestBytes, 0, requestBytes.Length);
}
//get the response
webResponse = webRequest.GetResponse();
using (var sr = new StreamReader(webResponse.GetResponseStream()))
{
returnVal = sr.ReadToEnd();
sr.Close();
}
}
catch (Exception ex)
{
errorMessage = ex.ToString();
}
finally
{
try
{
if (webRequest.GetRequestStream() != null)
webRequest.GetRequestStream().Close();
if (webResponse.GetResponseStream() != null)
webResponse.GetResponseStream().Close();
}
catch (Exception exw)
{
errorMessage = exw.ToString();
}
}
if the webRequest was created but a connection error happened during the
using (var sw = webRequest.GetRequestStream())
then the finally would catch an exception trying to close up connections it thought was open because the webRequest had been created.
If the finally didnt have a try-catch inside, this code would cause an unhandled exception while cleaning up the webRequest
if (webRequest.GetRequestStream() != null)
from there the code would exit without properly handling the error that happened and therefore causing issues for the calling method.
Hope this helps as an example
public void MyMethod()
{
try
{
}
catch{}
finally
{
CodeA
}
CodeB
}
The way the exceptions thrown by CodeA and CodeB are handled is the same.
An exception thrown in a finally block has nothing special, treat it as the exception throw by code B.
It throws an exception ;) You can catch that exception in some other catch clause.
Basically, what I want to do is pass a specific Exception to a more general Exception within the same try block. I've tried the following and it doesn't work:
static bool example(int count = 0)
{
try
{
work();
}
catch (TimeoutException e)
{
if (count < 3)
{
Console.WriteLine("Caught TimeoutException: {0}", e.Message);
return example(count + 1);
}
else
{
throw new Exception(e.Message);
}
}
catch (Exception e)
{
Console.WriteLine("Caught Exception: {0}", e.Message + " rethrown");
return false;
}
return true;
}
static void work()
{
throw new TimeoutException("test");
}
I want the TimeoutException to be only handled a certain amount of times before going to a more generic Exception. This is because the TimeoutException has additional information about the exception on a case by case basis. I do not want to duplicate the code for Exception under the else clause of TimeoutException. The reason I want all exceptions to be handled is that there may be other unknown exceptions that are thrown. The nature of the program requires it to not crash so I must account for any other exceptions and log them. How can I implement this?
You would need to nest this as 2 tries if you want to handle this this way:
static bool example(int count = 0)
{
try
{
try
{
work();
}
catch (TimeoutException e)
{
if (count < 3)
{
Console.WriteLine("Caught TimeoutException: {0}", e.Message);
return example(count + 1);
}
else
{
// Just throw, don't make a new exception
throw; // new Exception(e.Message);
}
}
}
catch (Exception e)
{
Console.WriteLine("Caught Exception: {0}", e.Message + " rethrown");
return false;
}
return true;
}
The "inner try/catch" will only catch TimeoutException, so any other exception will always go to the outer scope. When you rethrow, it'll automatically get caught by the outer scope, as well, which eliminates the need for killing the exception information. (If you throw new Exception, you lose your stack trace data, and other very valuable debugging information.)
Here's my take:
bool example()
{
// Attempt the operation a maximum of three times.
for (int i = 0; i < 3; i++)
{
try
{
work();
return true;
}
catch (Exception e)
{
Console.WriteLine("Caught exception {0}", e.Message);
// Fail immediately if this isn't a TimeoutException.
if (!(e is TimeoutException))
return false;
}
}
return false;
}
EDIT
If you want to actually do something with the TimeoutException, you could change the catch block like so:
catch (Exception e)
{
// As Reed pointed out, you can move this into the if block if you want
// different messages for the two cases.
Console.WriteLine("Caught exception {0}", e.Message);
TimeoutException timeoutException = e as TimeoutException;
if (timeoutException != null)
{
// Do stuff with timeout info...
}
else
{
// Not a timeout error, fail immediately
return false;
}
}