Hello everyone, I have a question, let's imagine that we have 3 classes, 1 of which is a C# Form, this form calls a method of class 2 and class 2 calls a method of class 3 that can throw an exception, my question en Where is it best to handle the exception of a method to display the error message to the user? In the form or in class 2?
//Ejemplo Form
private void MetodoForm(){
new Clase2().MetodoClase2();
//Mostrar Mensaje de error
//mas acciones
}
//Ejemplo Clase2
public void MetodoClase2(){
new Clase3().MetodoClase3();
//mas acciones
}
//Ejemplo Clase3
public void MetodoClase3(){
//puede causar una excepcion
File.WriteAllText("Texto");
//mas acciones
}
I have thought about this option but I feel that it does not make sense since I am generating an exception inside a catch
//Ejemplo Form
private void MetodoForm(){
try{
new Clase2().MetodoClase2();
//Mostrar Mensaje de error
//mas acciones
catch(ExcepcionCreadaPorMi e){//MostrarMensaje}
}
//Ejemplo Clase2
public void MetodoClase2(){
try{
new Clase3().MetodoClase3();
//mas acciones
}catch(IOException e){Throw new ExcepcionCreadaPorMi("Error al escribir el mensaje");}
}
//Ejemplo Clase3
public void MetodoClase3(){
//puede causar una excepcion
File.WriteAllText("Texto");
//mas acciones
}
As for showing the error to the user, it is recommended to do it in the form since you have tools like Messagebox.Show("message") that shows it on the screen or even being able to customize it. You would have three try catch blocks, one in each class where you would throw the exception "up" until the last try catch (in this case the form) and display it on the screen. Keep in mind that if you are the programmer and you see an error that is not very informative, it is difficult to know the origin and the details of the problem, but for these cases you can save the origin of the exception (class 3). the message in a log as a txt and there you will see the details of the problem (libraries like Log4net) Code:
I hope it has been helpful, Greetings!