c# - Some tips concerning exception handling would be appreciated -
not sure if should here or on code review, here goes!
i have little console application read in excel data of exceldatareader. code console application:
class program { static void main(string[] args) { somedata data = new somedata(@"c:\sc.xlsx", "somedata_2014"); ienumerable<sometype> sometypes = somedata.getdata(); console.readline(); } }
please don't worry naming of variables; company , don't want use company related. next somedata class:
public class somedata { private string path; private string worksheetname; public somedata(string path, string worksheetname) { this.path = path; this.worksheetname = worksheetname; } public ienumerable<sometype> getdata(bool isfirstrowascolumnnames = true) { var exceldata = new exceldata(path); try { var ad = exceldata.getdata(worksheetname, isfirstrowascolumnnames); return ad.select(datarow => new sometype() { gemeente = datarow["livingplace"].tostring(), geslacht = datarow["outdoors"].tostring(), woonplaats = datarow["wellhellyesorno"].tostring() }).tolist(); } catch (filenotfoundexception ex) { throw; } catch (argumentexception ex) { throw; } } }
and finally, exceldata class level lower somedata class:
public class exceldata { private string path; public exceldata(string path) { this.path = path; } private iexceldatareader getexceldatareader() { try { using (filestream filestream = file.open(path, filemode.open, fileaccess.read)) { iexceldatareader datareader = null; if (path.endswith(".xls")) { datareader = excelreaderfactory.createbinaryreader(filestream); } if (path.endswith(".xlsx")) { datareader = excelreaderfactory.createopenxmlreader(filestream); } return datareader; } } catch (filenotfoundexception ex) { console.writeline(ex); throw; } } public ienumerable<datarow> getdata(string sheet, bool isfirstrowascolumnnames = true) { var reader = getexceldatareader(); reader.isfirstrowascolumnnames = isfirstrowascolumnnames; var worksheet = reader.asdataset().tables[sheet]; var rows = datarow row in worksheet.rows select row; return rows; } }
what i'm trying do, when goes wrong e.g. opening excel file, throw exception, , bubble can write out @ top level.
the same goes getdata method of somedata class; @ moment want read data column , goes wrong, throw exception bubbles once again can write out @ top level.
i'm looking best way this.
exceptions "bubble" default; there's no point in rethrowing exception without doing anything, that's wasted code , cpu. in fact, that's pretty whole modus operandi of exceptions - whatever happens, wherever happens, bubble first guy ready handle it. need try { ... } catch (whateverexception ex) { ... }
@ point you're ready handle it.
any exceptions aren't handled @ kill application (although note frameworks winforms give option e.g. try , continue - in general, though, should handle anyway, it's final safety net).
Comments
Post a Comment