Link to home
Create AccountLog in
Avatar of WorknHardr
WorknHardr

asked on

ASP.NET Try Catch throw new ArgumentException Not Working?

I have great success with ArgumentException and C# desktop apps, but not having any success with asp.net webforms. The 'FileImport' class is in the App_Code folder and called by another FileImport.aspx.cs.

* The 'LoadDataset' method analyzes the imported file column header names with a string of correctl names. It does error if the '.Equals' returns false, but the ArgumentException is:
   1. Not sent to the FileImport.aspx.cs
      - or -
   2. Not caught correctly by the FileImport.aspx.cs.

- App_Code/FileImport.cs -

public DataTable LoadDataset(String path)
{
       if (!dbColumnNames.Equals(dtColumnNames))
       {
                return null;

                throw new ArgumentException("The Excel file columns are incorrect!");
       }
        return dt;
}


- FileImport.aspx.cs -

 protected void btnImport_Click(object sender, EventArgs e)
 {
        DataTable dt = new DataTable();
        FileImport fi = new FileImport(path);        
        try
        {
            dt = fi.LoadDataset(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + fileName));
        }
        catch (ArgumentException ex)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "ServerControlScript", "alert(" + ex.Message + ");", true);
 }

Open in new window

Avatar of Daniel Van Der Werken
Daniel Van Der Werken
Flag of United States of America image

You're returning before you hit that line of code.
do this:

public DataTable LoadDataset(String path)
{
       dt = null;
       if (!dbColumnNames.Equals(dtColumnNames))
       {
                throw new ArgumentException("The Excel file columns are incorrect!");
       }
        return dt;
}

Open in new window


or something like it. You are returning NULL before you hit the exception code.
Avatar of WorknHardr
WorknHardr

ASKER

Would this work too?
public DataTable LoadDataset(String path)
{
 If(!dbColumnNames.Equals(dtColumnNames))
       {
                throw new ArgumentException("The Excel file columns are incorrect!");
       }
}
The method returns a DataTable, so you need to do that somewhere within the method.

The key element here is that you make sure not to call the return before throwing the exception.

So, as written, the method you have would not even compile.
ASKER CERTIFIED SOLUTION
Avatar of WorknHardr
WorknHardr

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Note: The problem with the Javascript 'Alert' is not enough ' ' like so:

System.Web.UI.ScriptManager.RegisterStartupScript(this, this.GetType(), "ServerControlScript", "alert( ' " + ex.Message + " ' );", true);
Sorry, found my own solution, thx