Show message box in case of exception

I am wondering what the right way is to pass an exception from one method to my form.

public void test() { try { int num = int.Parse("gagw"); } catch (Exception) { throw; } } 

the form:

 try { test(); } catch (Exception ex) { MessageBox.Show(ex.Message); } 

this way i don't see my text box.

+6
source share
3 answers

If you only need a summary of the use of the exception:

  try { test(); } catch (Exception ex) { MessageBox.Show(ex.Message); } 

If you want to see the entire stack trace (usually better for debugging), use:

  try { test(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } 

Another method I've ever used:

  private DoSomthing(int arg1, int arg2, out string errorMessage) { int result ; errorMessage = String.Empty; try { //do stuff int result = 42; } catch (Exception ex) { errorMessage = ex.Message;//OR ex.ToString(); OR Free text OR an custom object result = -1; } return result; } 

And in your form you will have something like:

  string ErrorMessage; int result = DoSomthing(1, 2, out ErrorMessage); if (!String.IsNullOrEmpty(ErrorMessage)) { MessageBox.Show(ErrorMessage); } 
+11
source

There are many ways, for example:

First method:

 public string test() { string ErrMsg = string.Empty; try { int num = int.Parse("gagw"); } catch (Exception ex) { ErrMsg = ex.Message; } return ErrMsg } 

Method Two:

 public void test(ref string ErrMsg ) { ErrMsg = string.Empty; try { int num = int.Parse("gagw"); } catch (Exception ex) { ErrMsg = ex.Message; } } 
+1
source
  try { // your code } catch (Exception w) { MessageDialog msgDialog = new MessageDialog(w.ToString()); } 
0
source

Source: https://habr.com/ru/post/953899/


All Articles