If I have an error in the program and want to stop the program at that point and throw an exception with my error message, how can I do that? I have been trying to figure this out online, but all I see is throwing an exception with the built in messages.
Thanks,
Arep
Loading
A RepaskyPosted Mar 13, 2012, 5:16 PM
VulpesPosted Mar 13, 2012, 5:14 PM
So, basically, you need to enclose any call to a library method which can cause a 'fatal' exception (either directly or via a chain of other methods it calls) in a try/catch block within the exe.
If that's too tedious, you could also do it globally by handling the AppDomain.UnhandledException event in your exe.
This needs to be wired up when your Main() method starts:
static void Main(string[] args)
{
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += MyExceptionHandler;
MyClass mc = new MyClass();
mc.MyMethod();
// rest of code
}
static void MyExceptionHandler(object sender, UnhandledExceptionEventArgs args)
{
Exception ex = (Exception) args.ExceptionObject;
Console.WriteLine(ex.Message);
Console.WriteLine("Terminating application ...");
Environment.Exit(1);
}
Notice that this event will catch any uncaught exception, not just those of type MyException though it's possible to filter the latter out if needed.
A RepaskyPosted Mar 13, 2012, 4:39 PM
Thanks again.
Arep
VulpesPosted Mar 13, 2012, 3:22 PM
A RepaskyPosted Mar 13, 2012, 2:41 PM
A RepaskyPosted Mar 13, 2012, 2:21 PM
VulpesPosted Mar 13, 2012, 12:43 PM
throw new Exception(message);
'Exception' can be replaced by a more specific Exception type if you prefer.
If this exception is uncaught, then the application will terminate and display the message.