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

VulpesRank #55 · 29.2K reputationPosted Mar 13, 2012, 8:43 AM EDT
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.
A RepaskyRank #8,108 · 228 reputationPosted Mar 13, 2012, 10:21 AM EDT
if ((int)dr["cnt"] > 0) { myEx = "PieceID is zero for JobNumber " + jobID + " on " + dr["cnt"] + " records."; try { throw new MyException(myEx); } catch (Exception ex) { Console.WriteLine("Exception " + ex.ToString()); } } I want the program to stop at this point because of the error. This is in a library. I want the error or exception to be passed back to the calling program, then the program will stop and give the console message error. In other words, processing here go back to the main program then give the error. How can I do all this?A RepaskyRank #8,108 · 228 reputationPosted Mar 13, 2012, 10:41 AM EDT
VulpesRank #55 · 29.2K reputationPosted Mar 13, 2012, 11:22 AM EDT
A RepaskyRank #8,108 · 228 reputationPosted Mar 13, 2012, 12:39 PM EDT
Thanks again.
Arep
VulpesRank #55 · 29.2K reputationPosted Mar 13, 2012, 1:14 PM EDT
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 RepaskyRank #8,108 · 228 reputationPosted Mar 13, 2012, 1:16 PM EDT
if ((int)dr["cnt"] > 0) { string myEx = "PieceID is zero for JobNumber " + jobID + " on " + dr["cnt"] + " records."; throw new Exception(myEx); } Thanks, Arep