Last post Jul 20, 2016 08:11 AM by PatriceSc
Jul 19, 2016 03:50 PM|M.Beta|LINK
I have this assembly that basically create a memoerystream and then load an excel package with dataset in it. Now, I want to make a defense program so that it can handle whatever happens in case a person creates the memoerystream incorrectly.
Can someone show me how to do this?
Jul 19, 2016 07:35 PM|Mikesdotnetting|LINK
Another option is to throw an exception. For example, if the dataset is empty (has no tables) you might choose to throw an ArgumentException:
public static void CreateStream(ref MemoryStream mystream, DataSet ds)
if(ds.Tables.Count == 0)
throw new ArgumentException("The dataset is empty");
Jul 20, 2016 07:03 AM|Yohann Lu|LINK
From your description, you can try the following code.
public static bool CreateStream(ref MemoryStream mystream, DataSet ds, out string errormessage)
bool result = true;
errormessage = "";
int a = Convert.ToInt32("2A0");
//using (ExcelPackage package = new ExcelPackage(mystream))
// foreach (DataTable dt in ds.Tables)
// ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(dt.TableName);
// worksheet.Cells["A1"].LoadFromDataTable(dt, true);
catch (Exception ex)
result = false ;
errormessage = ex.Message;
protected void Button1_Click(object sender, EventArgs e)
MemoryStream ms = new MemoryStream();
DataSet ds = new DataSet();
string error = "";
bool res = CreateStream(ref ms, ds, out error);
Jul 20, 2016 08:11 AM|PatriceSc|LINK
It is usually considered as a bad idea. You turn an exception into two pieces of information and the caller could just ignore that (ie not check the bool return value) and the error message may not give that much details for debugging.
A best practice is to wrap the original exception into your own exception. For example if sending a SMTP message fails you have a StmpException with a "failure to send mail" message that allows first to know what failed in a block (ie sending the mail) and the
inner exception gives details if needed for diagnostic purpose.
https://msdn.microsoft.com/en-us/library/ms229049(v=vs.100).aspx and note also that "This practice should be used only in situations where the original exception is not meaningful to the person who receives the exception" (such as having a low level exception
when sending a mail).