I am beginner in C# programming. I have encountered small problem during building application using form. I will try to explain it properly within my abilities and experience. Problem uccured when i tried to handle exception caused by Class1 instantialized in my Form1. Let say i have function “public int Calc(int a, int b)” in Class1. In Form1 i have instantionalized this class to call its “Calc” function. If i want to message an error (f.e: divided by zero) i have to wrap function call into try/catch elements:
//Form1:
Class1 C1 = new Class1();
int a = 5;
int b = 0;
int c = 0;
try{
c = C1.Calc(a,b)
}
catch(DivideByZeroException e)
{
// some error handling code
}
… i think this example is not proper OOP technique so i had to decide to put try/catch elements directly into Class1:
//Class1:
public int Calc(int a, int b)
{
int c = 0;
try{
c = a/b;
}
catch(DivideByZeroException e)
{
// .........
}
return c;
}
… question is, how can i get message (DivideByZeroException e) into my Form1 to be able to handle it and message it. I don’t want to create some static function in Form1 just to reach MessageBox class in it from Class1 because it does not make sence in terms of proper OOP functionality and reusability of Class1. I have read about events and delegates (which i understand is simple pointer to function similar to C++) but it is somehow confusing and i failed to apply this technique into my code. Could you please write simple example which would point me to right direction.
thank You guys
Cembo
The proper technique really is the first one. If you can’t handle it inside your function, then you have no business trying. Put the exception handling in a place where the exception can be handled and the program can continue (or exit gracefully) and the user be notified of the error in an appropriate fashion.