I've heard the phrase:
"let the call stack unwind more than one level"
being mentioned in exception handling.
What does this mean?
Language in question is C#.
Thanks
I've heard the phrase:
"let the call stack unwind more than one level"
being mentioned in exception handling.
What does this mean?
Language in question is C#.
Thanks
In simplistic terms, you can think of the call stack working as follows:
So, when the call stack unwinds more than one level, more than one stack frame comes off at once — like a series of nested method calls (not just a single method call) returning.
In terms of exceptions:
Apologies for being a bit fast-and-loose with the terminology.
This means to let the exception exit the function that threw it and allow its caller to catch the function and deal with it.
As a general principle it is best to let the lowest possible method on the stack (specifically where it still has meaning or something can be done with it) catch an exception. This reduces redundant and otherwise unnecessary try...catch blocks and lets the code that can most appropriately handle an exception actually contain the logic to do so.
Update
Consider the following fairly general (and a bit contrived) example:
public abstract class ThrowRandomIOExceptions
{
public void SafeIOOperation(string fileName, IModel model)
{
try
{
DoSomeIOOperation(fileName, model);
}
catch(FileNotFoundException ex)
{
// Handle the exception so the children don't have to.
}
}
public abstract void DoSomeIOOperation(string fileName, IModel model);
}
public class WriteCSV : ThrowRandomIOExceptions
{
public void DoSomeIOOperation(string fileName, IModel model)
{
// Write the model in comma delimited format
}
}
public class WriteTSV : ThrowRandomIOExceptions
{
public void DoSomeIOOperation(string fileName, IModel model)
{
// Write the model in tab delimited format
}
}
Handling the FileNotFoundException
in the base class avoids the children from having to include their own try...catch and provides them the guarantee that exceptions from improper file names will be handled.