Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

exception handling 1

Status
Not open for further replies.

kevinprog

Programmer
Nov 27, 2005
2
CA
The following is for a windows application. If I was to cause a button click to throw an exception i.e.

private void button6_Click(object sender, System.EventArgs e)
{
//simulate a crash by throwing an exception
throw new Exception ("Simulated Crash");
}


where would I catch this other than in this function? I tried catching it in the Form's main fuction :

static void Main()
{
try
{
Application.Run(new Form1());
}
catch (Exception ex)
{
Console.WriteLine (ex.ToString());
}
}

but it seems like I can't catch it there.
 
the starting of the app must go in the:
[STAThread]
static void Main()
{
Application.Run(new Main_Startup());
}

//but to catch an exception you put a
try{
}
catch (exception e)

where ever you waant to catch an exception? hope this helps

Age is a consequence of experience
 
You need to add an exception handler to your AppDomain.
Code:
// in static Main method
AppDomain currentDomain = AppDomain.CurrentDomain;
   currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);

//handler
static void MyHandler(object sender, UnhandledExceptionEventArgs args) {
   Exception e = (Exception) args.ExceptionObject;
   Console.WriteLine("MyHandler caught : " + e.Message);
}
Note that in .net framework v1.1, it doesn't catch every single type of exception. They fixed this in v2.0

Chip H.


____________________________________________________________________
Donate to Katrina relief:
If you want to get the best response to a question, please read FAQ222-2244 first
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top