473,382 Members | 1,407 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,382 software developers and data experts.

Catch All Exceptions for Console Based Program

Recently, a thread appeared which asked how to create a "catch all" method
for when
an exception occurs within a program. The solution given only works for
Windows Forms applications, as far as i can tell, is it possible to do the
same with a console application?

Simon.
Nov 15 '05 #1
5 11063
put all code in Main() inside a try/catch(/finally) block.
Main is where your program starts and any exception not caught elsewhere
in your code will end up in main before your program crashes.

--
Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/
Nov 15 '05 #2
Morten,

That's not completely true. You can have multiple threads in a console
application, and if an exception is thrown on one of those threads, then you
will not catch it by wrapping the code in a try/catch block. Take for
example the following code:

static void Main(string[] args)
{
try
{
// Create a thread.
Thread pobjThread = new Thread(new ThreadStart(DoSomething));

// Start the thread.
pobjThread.Start();

// Wait five seconds.
Thread.Sleep(5000);
}
catch (Exception e)
{
Console.WriteLine("Exception on Main thread:")
Console.WriteLine(e);
}

// Get out.
return;
}

private static void DoSomething()
{
// Throw an exception.
throw new Exception();
}

This will crash and not be caught by the catch block.

Rather, you need to attach to the UnhandledException event on the
current AppDomain, like this:

static void Main(string[] args)
{
// Wire up an event handler for unhandled exceptions.
AppDomain.CurrentDomain.UnhandledException += new
UnhandledExceptionEventHandler(UnhandledException) ;

try
{
// Create a thread.
Thread pobjThread = new Thread(new ThreadStart(DoSomething));

// Start the thread.
pobjThread.Start();

// Wait five seconds.
Thread.Sleep(5000);
}
catch (Exception e)
{
Console.WriteLine(e);
}

// Get out.
return;
}

private static void UnhandledException(object sender,
UnhandledExceptionEventArgs e)
{
// Write the exception.
Console.WriteLine("AppDomain Unhandled Exception Event Handler:");
Console.WriteLine(e.ExceptionObject);
}

private static void DoSomething()
{
// Throw an exception.
throw new Exception();
}
}

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Morten Wennevik" <Mo************@hotmail.com> wrote in message
news:oprzyxozmvhntkfz@localhost...
put all code in Main() inside a try/catch(/finally) block.
Main is where your program starts and any exception not caught elsewhere
in your code will end up in main before your program crashes.

--
Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/
Nov 15 '05 #3
Yes, my solution will only work for a single threaded application.

--
Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/
Nov 15 '05 #4
-----Original Message-----
Recently, a thread appeared which asked how to create a "catch all" methodfor when
an exception occurs within a program. The solution given only works forWindows Forms applications, as far as i can tell, is it possible to do thesame with a console application?

Simon.
.


Vectored Exception Handling is a new exception mechanism
introduced in windows XP that allows you to catch
exceptions in a "Thread Independent" manner. See:

http://msdn.microsoft.com/msdnmag/is...9/hood/default
..aspx
for more information. You can also add your own "backstop"
to your application with by calling
SetUnhandledExceptionFilter on your process which will
allow you place a handler at the bottom of the exception
stack to execute when any exception propagates out far
enough. See:
http://msdn.microsoft.com/library/default.asp?
url=/library/en-
us/debug/base/setunhandledexceptionfilter.asp for more
information.

Jackson Davis [MSFT]
--

This posting is provided "AS IS" with no warranties, and
confers no rights.
Use of included script samples are subject to the terms
specified at
http://www.microsoft.com/info/cpyright.htm

Note: For the benefit of the community-at-large, all
responses to this
message are best directed to the newsgroup/thread from
which they
originated.

Nov 15 '05 #5
Or the simple way could be to use the AppDomain.UnhandledException event?
;-)

--
Eric Newton
C#/ASP Application Developer
http://ensoft-software.com/
er**@cc.ensoft-software.com [remove the first "CC."]

"Jackson Davis [MSFT]" <ja******@NOSPAM.online.microsoft.com> wrote in
message news:00****************************@phx.gbl...
-----Original Message-----
Recently, a thread appeared which asked how to create

a "catch all" method
for when
an exception occurs within a program. The solution given

only works for
Windows Forms applications, as far as i can tell, is it

possible to do the
same with a console application?

Simon.
.


Vectored Exception Handling is a new exception mechanism
introduced in windows XP that allows you to catch
exceptions in a "Thread Independent" manner. See:

http://msdn.microsoft.com/msdnmag/is...9/hood/default
.aspx
for more information. You can also add your own "backstop"
to your application with by calling
SetUnhandledExceptionFilter on your process which will
allow you place a handler at the bottom of the exception
stack to execute when any exception propagates out far
enough. See:
http://msdn.microsoft.com/library/default.asp?
url=/library/en-
us/debug/base/setunhandledexceptionfilter.asp for more
information.

Jackson Davis [MSFT]
--

This posting is provided "AS IS" with no warranties, and
confers no rights.
Use of included script samples are subject to the terms
specified at
http://www.microsoft.com/info/cpyright.htm

Note: For the benefit of the community-at-large, all
responses to this
message are best directed to the newsgroup/thread from
which they
originated.

Nov 15 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: thechaosengine | last post by:
Hi everyone, Is there anyway to create some sort of catch-all in windows forms applications that could ensure that no unexpected exceptions bring down an application? For example, perhaps...
4
by: Abhishek Srivastava | last post by:
Hello All, I have seen code snippets like try { ..... } catch {
8
by: Z D | last post by:
Hi, I was wondering what's the point of "finally" is in a try..catch..finally block? Isn't it the same to put the code that would be in the "finally" section right after the try/catch block?...
11
by: Tamas Demjen | last post by:
I was shocked to learn that VC++ 2005 Beta 2 can't catch Access Violation exceptions in unmanaged code. To reproduce this, I created a minimal Win32 console application: #include "stdafx.h" ...
23
by: VB Programmer | last post by:
Variable scope doesn't make sense to me when it comes to Try Catch Finally. Example: In order to close/dispose a db connection you have to dim the connection outside of the Try Catch Finally...
22
by: STom | last post by:
I heard someone mention to me that the use of try catch exception handling is very expensive (in relative terms of slowing an app down) if it is used frequently. Of course they could not explain...
32
by: cj | last post by:
Another wish of mine. I wish there was a way in the Try Catch structure to say if there wasn't an error to do something. Like an else statement. Try Catch Else Finally. Also because I...
13
by: DaTurk | last post by:
What's the CLI equivalent of the empty catch? i.e. try{} catch {}
3
by: Miro | last post by:
I cant seem to find an example on how to do something, ( vb2005.express ) i have a Try ListeningSerialPort.Open() TestText.Enabled = True Catch ex As Exception 'Debug.WriteLine(ex.Message)...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.