Catch an exception thrown by another form

I am trying to do this:

I create another form, which in it the FormClosed method throws an exception that must be caught by the main form.

Basic form:

try { frmOptions frm = new frmOptions(); frm.ShowDialog(); } catch(Exception) { MessageBox.Show("Exception caught."); } 

frmOptions:

 private void frmOptions_FormClosed(object sender, FormClosedEventArgs e) { throw new Exception(); } 

The debugger stops on an exception with this message:

Exception was not handled by user code

Why? I caught the exception from the owner of the object that created it. Does anyone have an idea?

+4
source share
4 answers

I don’t think this might work, the new form does not work in the context of your code above, it only runs it. If you check stacktrace for the thrown exception, you will not see the code above, so it will not be able to catch the exception.

Update: I just created a test project and tried it. The glass system knows nothing about the original form. If you want to catch unhandled exceptions, you can check this question Unhandled Exception Handler in .NET 1.1

+2
source

you can handle all exceptions in your project from program.cs

 static class Program { [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); AppDomain.CurrentDomain.UnhandledException += AppDomain_UnhandledException; Application.ThreadException += Application_ThreadException; Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); Application.Run(new MainMDI()); } static void Application_ThreadException(Object sender, ThreadExceptionEventArgs e) { MessageBox.Show(e.Exception.Message, "Application.ThreadException"); } static void AppDomain_UnhandledException(Object sender, UnhandledExceptionEventArgs e) { MessageBox.Show(((Exception)e.ExceptionObject).Message, "AppDomain.UnhandledException"); } } 
+2
source

You can do this as follows:

 public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Form2 form2 = new Form2(this); form2.Show(); } public void HandleForm2Exception(Exception ex) { MessageBox.Show("EXCEPTION HAPPENED!"); } } 

and on Form2.cs

 public partial class Form2 : Form { private Form1 form1; public Form2(Form1 form1) : this() { this.form1 = form1; } public Form2() { InitializeComponent(); } private void Form2_FormClosed(object sender, FormClosedEventArgs e) { try { throw new Exception(); } catch (Exception ex) { if(this.form1 != null) this.form1.HandleForm2Exception(ex); } } } 
+1
source

Why are you trying to make an exception from one form to another? "Do not throw a new exception ()"

If you want the main form to know that the parameter form is closed, you can simply have a flag in the main form that is set from the parameter form.

+1
source

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


All Articles