exception handling in class libraries
-
When designing classes is it a best practice to do exception handling within class or should it be taken care of at the UI level? In other words if my class is in ClassLibrary project should I check and throw exceptions there like this:
public MyClass { public MyClass(){...} GetSomeDataById(string id) { try { // Open connection and all that good stuff ... } Catch { /* Catch*/ } finallay { /* close connection */ } } } -------------------------------------------------------------- // in .aspx file MyClass myClass = new MyClass("whatever"); string someData = myClass.GetSomeDataGyId("10"); if(String.IsNullOrEmply(someData) { // Some code }
or should I do something like this:
public MyClass { public MyClass(){...} GetSomeDataById(string id) { // Open connection and all that good stuff .... // close connection } } ------------------------------------------------- //in aspx file try { MyClass myClass = new MyClass("whatever"); string someData = myClass.GetSomeDataGyId("10"); if(String.IsNullOrEmply(someData) { // Some code } } catch Exception(e) { // Call some function to display this message }
-
When designing classes is it a best practice to do exception handling within class or should it be taken care of at the UI level? In other words if my class is in ClassLibrary project should I check and throw exceptions there like this:
public MyClass { public MyClass(){...} GetSomeDataById(string id) { try { // Open connection and all that good stuff ... } Catch { /* Catch*/ } finallay { /* close connection */ } } } -------------------------------------------------------------- // in .aspx file MyClass myClass = new MyClass("whatever"); string someData = myClass.GetSomeDataGyId("10"); if(String.IsNullOrEmply(someData) { // Some code }
or should I do something like this:
public MyClass { public MyClass(){...} GetSomeDataById(string id) { // Open connection and all that good stuff .... // close connection } } ------------------------------------------------- //in aspx file try { MyClass myClass = new MyClass("whatever"); string someData = myClass.GetSomeDataGyId("10"); if(String.IsNullOrEmply(someData) { // Some code } } catch Exception(e) { // Call some function to display this message }
If you are using the class from more than one location and the messages might be different for different locations then you should throw the exception from the class. You should log the exact location of exception in log file so that you must know the origin of the exception. I hope it will solve your problem. Good luck.