Link to home
Start Free TrialLog in
Avatar of cfg1980
cfg1980

asked on

VB.NET --- Exit Program on Error

I'm attempting to write a VB.Net program where if any of my code returns an error, the program closes.  Here's what I'm trying, but its not working.  I've tried both Application.Exit() and Me.Close().  Neither seems to work, the program just continues on.  Can someone please tell me what I'm doing wrong?


Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

  'call the main funtion
  theFunction()

End Sub


Private Sub theFunction

 Try
   here's where my code goes
 Catch
   'there was an error, need to quit the program
   QuitApp()
 End Try

End Sub


Private Sub QuitApp()

 here's where my code goes to close all open objects

 Application.Exit()

End Sub
ASKER CERTIFIED SOLUTION
Avatar of Dirk Haest
Dirk Haest
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of cfg1980
cfg1980

ASKER

System.Windows.Forms.Application.Exit() worked for me.  Thank you
Avatar of cfg1980

ASKER

Opps sorry, I meant System.Environment.Exit(-1) worked for me....not the Application.Exit()
Hi cfg1980;

The default Shutdown mode for a Windows Form application is "When startup form is closed." In .Net Framework 2.0 and before this can be changed to "When last form closes." In .Net 3.0 they added a third option which is "On Explicit Shutdown" which the application only shuts down when Application.Shutdown() or Application.Shutdown(int32) where the int32 is the return code is called.

The class that has the function "Private Sub theFunction" if it is in the form that the program starts on then this should work, Me.Close(), If not then you need a reference to the main form so that you can close it with the Me.Close() method.

Fernando
Hi cfg1980;

A couple of issues with using System.Environment.Exit(-1). The Form.Closing or Form.Closed methods are not called and so any cleanup of all open forms need to be done individually. The other thing is that according to Microsoft System.Environment.Exit(-1) can cause a SecurityException - if "The caller does not have sufficient security permission to perform this function. " so check out the code.

Fernando