473,765 Members | 2,010 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Throwing exception in a try block?

is it a bad programming design to throw exception in the try block then
catch it??
Nov 17 '05
40 13530
John

"No, it is not a good idea to wrap everything in a try/catch block. Don't
use try/catch unless you have a real reason to catch an exception or
cleanup
(finally). What does the catch do? If it just rethrows the exception,
then
you're wasting your effort, making your code hard to read and not adding
any
value."

In the catch block, the error will be log to the windows event log, then the
exception
is wrapped into a custom exception and rethrown. not sure if this is a good
idea.

There are different type of exception, if it's application critical input
parameters such
as those read from the application config file/console input (console app
called by
windows service by spawning a process and pass parameters), if those values
are incorrect or corrupted which
are unlikely, then an exception should be thrown to stop the execution. with
the throwing
exception in the try catch block, it will easy stop the application whenever
a parameter
is incorrect. I mean using goto or continue statement will do but in terms
of handling the situation,
I think throwing exception will make more sense.

so in this case, do this:

try
{
if (error)
throw new exception("Erro r");
}
catch (Exception ex)
{
Logerror();
}
won't be so bad.

"John Vottero" <Jo**@mvpsi.com > wrote in message
news:eu******** ******@TK2MSFTN GP10.phx.gbl...
"Kevin Yu" <ko**@hotmail.c om> wrote in message
news:e9******** ********@tk2msf tngp13.phx.gbl. ..
John

don't get me wrong, I just want some justice on someone else's code that I need to follow and support.

basically he wrap everything in try catch block even when instantiating a new object, he will check for if the newly created object is null, then
throw and exception, I mean if the new operate fail to instantiate an
instance aka it's out of memory, the runtime will throw and
OutofMemoryExce ption, the guys is clearly came from a C++ background.
anyway, is it a good idea to wrap everything inside a try catch block, I
No, it is not a good idea to wrap everything in a try/catch block. Don't
use try/catch unless you have a real reason to catch an exception or

cleanup (finally). What does the catch do? If it just rethrows the exception, then you're wasting your effort, making your code hard to read and not adding any value.

You might remind this guy that he can still check things and throw
exceptions without wrapping the code in a try/catch.
read somewhere that try block doesn't cost anything, only when exception
occur, it will cost u, so does that mean it's a good idea to wrap
everything


That is true, try/catch is almost free until an exception is thrown.
in try catch, I mean hack, this will make the system *Robus*.

enlighten me.

Kevin

"John Vottero" <Jo**@mvpsi.com > wrote in message
news:Of******** ******@TK2MSFTN GP09.phx.gbl...
"Kevin Yu" <ko**@hotmail.c om> wrote in message
news:eU******** ******@TK2MSFTN GP14.phx.gbl...
> is it a bad programming design to throw exception in the try block then > catch it??
>

It depends on what you're doing and why you're doing it. If you're

catching
exceptions so that you can do some sort of rollback or cleanup and then
throw (or rethrow) an exception then it could be a fine design. If
you're
throwing and catching as a neat-o way of passing data then, it's a bad
design.

What are you doing?



Nov 17 '05 #21
Kevin Yu wrote:
In the catch block, the error will be log to the windows event log, then the
exception
Okay, that's reasonable... if you expect the caller to just die or
mishandle the exception.
is wrapped into a custom exception and rethrown. not sure if this is a good
idea.
Now *that*'s my favorite hate-thing on exceptions!

What does wrapping it help the caller? Logging certainly didn't produce
any additional information the caller would like to have.

More importantly, you have robbed the caller of the possibility to catch
the exception by type, just use:

catch ( Exception e ) {
Log(e);
throw;
}

(As you may be able to tell, this is not my first discussion on the
subject :)
try
{
if (error)
throw new exception("Erro r");
}
catch (Exception ex)
{
Logerror();
}


I really don't like that, it's just a very complicated way of doing
goto, and there are better options: write one logging handler at the
call-stack top, and then use exceptions to signal errors, knowing that
someone will catch, log, and whatever they feel is approrpriate.

static int _Main(string args[]) {
// just code along, and throw INFORMATIONAL errors
// if anything goes wrong.
if ( error )
throw new ParsingExceptio n(
string.Format(" Invalid argument {0}", arg))
// ...
return 0;
}

static int Main(string args[]) {
#if !DEBUG
try {
#endif
return _Main(args);
#if !DEBUG
} catch ( Exception e ) {
Log(e);
throw;
#endif
}

The (#if !DEBUG) allows you to use the "break if not catched" setting in
the IDE usefully. You could use another symbol, DEBUG is just *so* handy
for me :)

This pattern is also pretty usefull when testing:

void Test() {
string[] valid_args = { "x" };
string[] invalid_args = { "y" };

AssertEquals(_M ain(valid_args) , 0);

ParseException threw = null;
try {
_Main(invalid_a rgs);
} catch ( ParseException e ) {
threw = e;
}
AssertNull(Pars eException);
}

--
Helge Jensen
mailto:he****** ****@slog.dk
sip:he********* *@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-
Nov 17 '05 #22

Helge Jensen wrote:
Retrying an operation, for example:

- When a protocol over an unreliable media comes out of sync.
- When a modem dial-up fails
- When a user can be asked to enter another possibility
Touché :)
Which is a kind of "else-if-by-error".

This kind of "recovery-by-default" is usually not a good idea (atleast in the long run) since it removes the possibility of the caller noticing that the default was chosen instead of the selected value (which was
misspelled and thus gave a parse-error).
Well, in this particular case, it would have been great if the
framework contained a sort of "CanParse" function. So instead of
calling Int32.Parse and bracing for the exception to hit, I would have
preferred to call Int32.CanParse and THEN do some action.
Well,... yes -- but sometimes components wish to keep separate logs of unexpected errors

Touché again.

Nov 17 '05 #23
Well, in this particular case, it would have been great if the
framework contained a sort of "CanParse" function. So instead of
calling Int32.Parse and bracing for the exception to hit, I would have
preferred to call Int32.CanParse and THEN do some action.


There is ...

double.TryParse () and there are arguments that let you specify the data
type.

Whidbey has more methods besides that one.

Nov 17 '05 #24

What does wrapping it help the caller? Logging certainly didn't produce
any additional information the caller would like to have.

More importantly, you have robbed the caller of the possibility to catch
the exception by type, just use:

catch ( Exception e ) {
Log(e);
throw;
}

Except that in v1.1 using a naked throw causes the stack trace to get reset,
so you lose that information.

I prefer to catch-wrap-throw, as nothing is lost and you can add context
information. I use a helper method to
rethrow the original exception type, as in...

catch(Exception ex)
{
throw CloneException( "Context info.",ex);
}

This preserves the original exception type, the stack trace info, and adds
additional meaning.

I really don't like that, it's just a very complicated way of doing goto,
and there are better options: write one logging handler at the call-stack
top, and then use exceptions to signal errors, knowing that someone will
catch, log, and whatever they feel is approrpriate.


I prefer a log twice option, the first time at the original site where the
exception was caught, and once again at the top. The reason is to catch code
paths where an exception is inadvertently swallowed on its way up the call
stack. This can be a problem in a large project with many different
components written by different developers - no one person has personal
knowledge of every piece of code in the system.

Nov 17 '05 #25
David Levine wrote:
Except that in v1.1 using a naked throw causes the stack trace to get reset,
so you lose that information.
Yes, that's a bug. But the original trace is in the log, that's why you
did the catch, so it's not that bad.
I prefer to catch-wrap-throw, as nothing is lost and you can add context
information. I use a helper method to
rethrow the original exception type, as in...

catch(Exception ex)
{
throw CloneException( "Context info.",ex);
}
That's not really wrapping, is it? That's working around the
"throw;"-bug. At least if you really are "cloning" ex.

A nice workaround :)
This preserves the original exception type, the stack trace info,
yes.
and adds
additional meaning.


Only if the "Context info" doesn't shadow the information in ex, but is
made available on enquery.

It's a nice trick though, It (in effect) allows adding notes to an
exception in the form of objects not available at the error-site, but
non-theless important to understanding the error as the exception
bubbles the call-stack.
I really don't like that, it's just a very complicated way of doing goto,
and there are better options: write one logging handler at the call-stack
top, and then use exceptions to signal errors, knowing that someone will
catch, log, and whatever they feel is approrpriate.


I prefer a log twice option, the first time at the original site where the
exception was caught, and once again at the top. The reason is to catch code
paths where an exception is inadvertently swallowed on its way up the call
stack. This can be a problem in a large project with many different
components written by different developers - no one person has personal
knowledge of every piece of code in the system.


I recognize this problem, people writing:

try {
f();
} catch {};

should get a *very* serious talking-to.

But how does the above help you with that?

It must be a very involved logfile-analysis to extract the relevant
information, especially since there is nothing that warns you this may
be the problem. The program explicitly *doesn't* terminate.

How do you skip all the places where actual error-handling is done?

--
Helge Jensen
mailto:he****** ****@slog.dk
sip:he********* *@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-
Nov 17 '05 #26
David,
| I prefer a log twice option, the first time at the original site where the
| exception was caught, and once again at the top. The reason is to catch
code
Have you looked at the new .NET 2.0 AppDomain events pertaining to
Exceptions?

http://msdn2.microsoft.com/library/1dw188c1.aspx

Such as CatchingExcepti on & ExceptionThrown . I have not tried it, reading
about ExceptionThrown , it sounds like it may allow one to log the exception
at the original site, instead of splattering your code with a lot of Catch
blocks...

I would be curious on your take on the exceptions after you have had a
chance to use them.

Just a thought
Jay
"David Levine" <no************ ******@wi.rr.co m> wrote in message
news:uT******** ******@TK2MSFTN GP10.phx.gbl...
|
| >
| > What does wrapping it help the caller? Logging certainly didn't produce
| > any additional information the caller would like to have.
| >
| > More importantly, you have robbed the caller of the possibility to catch
| > the exception by type, just use:
| >
| > catch ( Exception e ) {
| > Log(e);
| > throw;
| > }
| >
|
| Except that in v1.1 using a naked throw causes the stack trace to get
reset,
| so you lose that information.
|
| I prefer to catch-wrap-throw, as nothing is lost and you can add context
| information. I use a helper method to
| rethrow the original exception type, as in...
|
| catch(Exception ex)
| {
| throw CloneException( "Context info.",ex);
| }
|
| This preserves the original exception type, the stack trace info, and adds
| additional meaning.
|
| >
| > I really don't like that, it's just a very complicated way of doing
goto,
| > and there are better options: write one logging handler at the
call-stack
| > top, and then use exceptions to signal errors, knowing that someone will
| > catch, log, and whatever they feel is approrpriate.
|
| I prefer a log twice option, the first time at the original site where the
| exception was caught, and once again at the top. The reason is to catch
code
| paths where an exception is inadvertently swallowed on its way up the call
| stack. This can be a problem in a large project with many different
| components written by different developers - no one person has personal
| knowledge of every piece of code in the system.
|
|
|
|
|
Nov 17 '05 #27

"Helge Jensen" <he**********@s log.dk> wrote in message
news:42******** ******@slog.dk. ..
Kevin Yu wrote:
In the catch block, the error will be log to the windows event log, then the exception
Okay, that's reasonable... if you expect the caller to just die or
mishandle the exception.
is wrapped into a custom exception and rethrown. not sure if this is a good idea.


Now *that*'s my favorite hate-thing on exceptions!

What does wrapping it help the caller? Logging certainly didn't produce
any additional information the caller would like to have.

well, I think the purpose of making a custom exception is to include more
information for the exception,
sometimes, people want to log and error source such as the machine name or
IP, information like that.
and use the original exception as inner exception.


More importantly, you have robbed the caller of the possibility to catch
the exception by type, just use:

catch ( Exception e ) {
Log(e);
throw;
}

(As you may be able to tell, this is not my first discussion on the
subject :)
try
{
if (error)
throw new exception("Erro r");
}
catch (Exception ex)
{
Logerror();
}


I really don't like that, it's just a very complicated way of doing
goto, and there are better options: write one logging handler at the
call-stack top, and then use exceptions to signal errors, knowing that
someone will catch, log, and whatever they feel is approrpriate.

static int _Main(string args[]) {
// just code along, and throw INFORMATIONAL errors
// if anything goes wrong.
if ( error )
throw new ParsingExceptio n(
string.Format(" Invalid argument {0}", arg))
// ...
return 0;
}

static int Main(string args[]) {
#if !DEBUG
try {
#endif
return _Main(args);
#if !DEBUG
} catch ( Exception e ) {
Log(e);
throw;
#endif
}

The (#if !DEBUG) allows you to use the "break if not catched" setting in
the IDE usefully. You could use another symbol, DEBUG is just *so* handy
for me :)

This pattern is also pretty usefull when testing:

void Test() {
string[] valid_args = { "x" };
string[] invalid_args = { "y" };

AssertEquals(_M ain(valid_args) , 0);

ParseException threw = null;
try {
_Main(invalid_a rgs);
} catch ( ParseException e ) {
threw = e;
}
AssertNull(Pars eException);
}

--
Helge Jensen
mailto:he****** ****@slog.dk
sip:he********* *@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-

Nov 17 '05 #28
try
{
if (error)
throw new exception("Erro r");
}
catch (Exception ex)
{
Logerror();
}
I really don't like that, it's just a very complicated way of doing
goto, and there are better options: write one logging handler at the
call-stack top, and then use exceptions to signal errors, knowing that
someone will catch, log, and whatever they feel is approrpriate.

I don't know if it's a bug or not, in a timer_elapsed event handler, if an
exception occur,
it won't bubble back to the caller, since it's running in another thread, so
if there is
no try catch block to handle the exception in the elapsed event handler and
returning a value,
then the user won't event know exception occur in the handler.

[STAThread]

static void Main(string[] args)

{
System.Timers.T imer myTimer = new System.Timers.T imer(5000);
myTimer.Elapsed +=new System.Timers.E lapsedEventHand ler(myTimer_Ela psed);

myTimer.Start() ;

Console.ReadLin e();

}

private static void myTimer_Elapsed (object sender,
System.Timers.E lapsedEventArgs e)

{

Console.WriteLi ne("Time elapsed");

throw new Exception("Exce ption from elapsed event handler");

}

static int _Main(string args[]) {
// just code along, and throw INFORMATIONAL errors
// if anything goes wrong.
if ( error )
throw new ParsingExceptio n(
string.Format(" Invalid argument {0}", arg))
// ...
return 0;
}

static int Main(string args[]) {
#if !DEBUG
try {
#endif
return _Main(args);
#if !DEBUG
} catch ( Exception e ) {
Log(e);
throw;
#endif
}

The (#if !DEBUG) allows you to use the "break if not catched" setting in
the IDE usefully. You could use another symbol, DEBUG is just *so* handy
for me :)

This pattern is also pretty usefull when testing:

void Test() {
string[] valid_args = { "x" };
string[] invalid_args = { "y" };

AssertEquals(_M ain(valid_args) , 0);

ParseException threw = null;
try {
_Main(invalid_a rgs);
} catch ( ParseException e ) {
threw = e;
}
AssertNull(Pars eException);
}

--
Helge Jensen
mailto:he****** ****@slog.dk
sip:he********* *@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-

Nov 17 '05 #29
Doh!
| I would be curious on your take on the exceptions after you have had a
| chance to use them.
I would be curious on your take on the new exception events after you have
had a chance to use them.

Jay

"Jay B. Harlow [MVP - Outlook]" <Ja************ @msn.com> wrote in message
news:Og******** ********@TK2MSF TNGP10.phx.gbl. ..
| David,
|| I prefer a log twice option, the first time at the original site where
the
|| exception was caught, and once again at the top. The reason is to catch
| code
| Have you looked at the new .NET 2.0 AppDomain events pertaining to
| Exceptions?
|
| http://msdn2.microsoft.com/library/1dw188c1.aspx
|
| Such as CatchingExcepti on & ExceptionThrown . I have not tried it, reading
| about ExceptionThrown , it sounds like it may allow one to log the
exception
| at the original site, instead of splattering your code with a lot of Catch
| blocks...
|
| I would be curious on your take on the exceptions after you have had a
| chance to use them.
|
| Just a thought
| Jay
|
|
| "David Levine" <no************ ******@wi.rr.co m> wrote in message
| news:uT******** ******@TK2MSFTN GP10.phx.gbl...
||
|| >
|| > What does wrapping it help the caller? Logging certainly didn't produce
|| > any additional information the caller would like to have.
|| >
|| > More importantly, you have robbed the caller of the possibility to
catch
|| > the exception by type, just use:
|| >
|| > catch ( Exception e ) {
|| > Log(e);
|| > throw;
|| > }
|| >
||
|| Except that in v1.1 using a naked throw causes the stack trace to get
| reset,
|| so you lose that information.
||
|| I prefer to catch-wrap-throw, as nothing is lost and you can add context
|| information. I use a helper method to
|| rethrow the original exception type, as in...
||
|| catch(Exception ex)
|| {
|| throw CloneException( "Context info.",ex);
|| }
||
|| This preserves the original exception type, the stack trace info, and
adds
|| additional meaning.
||
|| >
|| > I really don't like that, it's just a very complicated way of doing
| goto,
|| > and there are better options: write one logging handler at the
| call-stack
|| > top, and then use exceptions to signal errors, knowing that someone
will
|| > catch, log, and whatever they feel is approrpriate.
||
|| I prefer a log twice option, the first time at the original site where
the
|| exception was caught, and once again at the top. The reason is to catch
| code
|| paths where an exception is inadvertently swallowed on its way up the
call
|| stack. This can be a problem in a large project with many different
|| components written by different developers - no one person has personal
|| knowledge of every piece of code in the system.
||
||
||
||
||
|
|
Nov 17 '05 #30

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

Similar topics

2
2170
by: Hank | last post by:
Please help me diagnose the following problem. I have a Swing program (running under 1.4.2_04) that uses JNI to get some hardware-level information and return that info as a csv String. The String returns and I am able to run .split() on it. At some point after that (this seems to vary), my program simply exits during the middle of execution. I've peppered the code with println() statements and the program appears to be exiting after a...
2
1515
by: SK | last post by:
What is the purpose of throwing exceptions in catch block. Bcos the exception is already thrown only, it is coming to the catch block.What is the purpose of throwing it again then!!!.....Help
21
7286
by: Stephan | last post by:
why does the following code not work???? after compiling and running it will just say killed after all my memory filled up any suggestions? #include <iostream> using namespace std; void out_of_mem() {
1
1670
by: Farooq Khan | last post by:
i'm writing a class library having following code snippet. i want this class to report an error (by throwing an Exception) to the application using this class library. the problem is that within that try block there are several exceptions that this class itself needs to handle (interrnally). now when the exception, UserAlreadyRegistered, is thrown the class' catch block (within library) catches it and no exception is thrown to the...
5
2009
by: KJ | last post by:
This is kind of hard to explain but I have a The controls are created with CreateChildControls(). Now let say I click a button and an error occurs in the control. If I throw it up it goes back to the web form. where do I catch the exception at? Example Webform Composite Control
1
4044
by: paul.hine | last post by:
Hello, I maintain an application that pulls data from a web service and writes it to an Excel sheet. Originally, the app used OleDb to write the Excel. Exports ran fine except that some text fields were truncated due to the 255 character limit of the Jet Excel driver. To overcome this limit, I decided to just generate CSV directly. This is where my trouble began. First I tried the StreamWriter class, implemented as per the "How to:
5
4596
by: Mike | last post by:
Hello All, Please, if anyone can point me to the problem, I'd sure appreciate it! I am very new to VB programming and not a programmer to begin with. This is part of a Visual Basic 2005 Express Edition program to control a remote basketball scoreboard display unit. All I'm trying to do is add 5 byte variables and store the result in an integer variable. I added a Try/Catch block to take look at things. This exception occurs only when...
3
13943
by: =?Utf-8?B?SGVtaWw=?= | last post by:
Hi, I have written a web service for accessing data from a database. I have a method in the webservice which returns a dataset. I am trying to implement error handling by using the try...catch...finally structure. Now, the method's logic in the try block returns a dataset while the the code in the 'catch' block throws an exception object of the SoapException class. Before, returning an exception to the calling code, I build up an...
21
1720
by: Chris M. Thomasson | last post by:
Is it every appropriate to throw in a dtor? I am thinking about a simple example of a wrapper around a POSIX file... ________________________________________________________________________ class file { FILE* m_handle; public: // ; ~file() /* throw() */ {
0
9568
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10163
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10007
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
7379
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6649
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5423
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3924
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3532
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2806
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.