473,848 Members | 1,628 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 13553
My opinion is that this can be used sparingly when it makes the code
flow
easier to read. So if I have a catch that basically returns false on an
error, sets
an error message etc. and I have a invariant error that should also
return
false, then it is very simple to throw an exception on an invariant
error and
just reuse the code block in the catch. In other words, I think
throwing an
exception in the try block is acceptable when it makes the code easier
to read
and follow and understand what is going on. Else I don't throw
exceptions in
try.

Regards,
Jeff
is it a bad programming design to throw exception in the try block then
catch it??
*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 17 '05 #11
Miha,

good to hear from you again, I think you help me out couple of years ago on
the dataset stuff, nice to see you are active in this newsgroup.
Kevin

"Miha Markic [MVP C#]" <miha at rthand com> wrote in message
news:uy******** ******@TK2MSFTN GP15.phx.gbl...
Hi Kevin,

Depends. For example, if you have a deeply nested procedure, throwing an
exception to exit might be a viable way.
However, normally throwing an exception is costly plus throwing an
exception should signal an error.

--
Miha Markic [MVP C#] - RightHand .NET consulting & development
www.rthand.com
SLODUG - Slovene Developer Users Group www.codezone-si.info

"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??


Nov 17 '05 #12

"Jeff Louie" <je********@yah oo.com> wrote in message
news:e1******** ******@TK2MSFTN GP12.phx.gbl...
My opinion is that this can be used sparingly when it makes the code
flow
easier to read. So if I have a catch that basically returns false on an
error, sets
an error message etc. and I have a invariant error that should also
return
false, then it is very simple to throw an exception on an invariant
error and
just reuse the code block in the catch. In other words, I think
throwing an
exception in the try block is acceptable when it makes the code easier
to read
and follow and understand what is going on. Else I don't throw
exceptions in
try.

throwing an exception in the try block is costly, it slows down the prog,
yea, it make the code easier to read,
I think with a better refactory technique such design can be avoided. in my
case ( the code I am reading) it's messy
because even in the catch block, and try catch block is also there in case
of the exception occur in the catch block from
writing the error to eh event log. I mean how many level of exception
handling u need.

making the program easier to read doesn't mean you can throw exceptions
freely, for example, in the main function, there is a
try can catch block, then in the try catch, there are bunch of high level
function calls, within those functions, a try catch block
is used to handle any exception that might occur, but then after handling
the exception, e.g write error event log or email people
the function will throw the exception/bubble it up to the main function, in
stead of doing that, why doesn't it just return a bool
then base on the boolean an if statement can direct the program flow instead
of getting to the exception handler that way, sometimes
there is a finally block to clean up stuff, if and object didn't even get
instantiated or started because of the proceeding exception, then no need to
do the
clean up for those object, I mean sure you can use if statement to check if
not null or something before cleaning up or aborting a thread, then
where is the efficiency?



Regards,
Jeff
is it a bad programming design to throw exception in the try block then
catch it??
*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!

Nov 17 '05 #13
Kevin Yu <ko**@hotmail.c om> wrote:
throwing an exception in the try block is costly, it slows down the
prog, yea, it make the code easier to read, I think with a better
refactory technique such design can be avoided. in my case ( the code
I am reading) it's messy because even in the catch block, and try
catch block is also there in case of the exception occur in the catch
block from writing the error to eh event log. I mean how many level
of exception handling u need.


Throwing an exception is *slightly* costly - but not very expensive
really. You don't want to start doing it in a short loop, for instance,
but exceptions aren't nearly as expensive as a lot of people seem to
think. In the very rare cases where it makes the code significantly
more readable, I'd hold that as more important than performance until
it was proven that that bit of code was an application bottleneck and
that the exceptions were the problem.

As an example of how overblown the issue of the performance penalty for
exceptions is, on another group a while ago someone was asking whether
or not his application was suffering because it was throwing a couple
of hundred exceptions per *hour*. Many people said that yes, this was
probably slowing his application down significantly. My laptop can
throw a hundred thousand exceptions per *second* - in other words, his
200 exceptions would take less than a millionth of the hour in which
they were thrown.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #14
Mohammad wrote:
Helge,

If you don't mind, I would like to add that, from my own experience, I
have yet to come across a case where anything can be done to remedy an
error flagged by an excpetion.
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
that is actually doable is in the case of parsing strings to other data
types, in which case the error can be corrected by setting the target
variable to some sensible default.
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).
So, again from my own experience, the best thing to do in the case of
an exception is to simply roll back any changes done within the scope
of the operation and letting the excpetion bubble up to the caller.
I couldn't agree more :)

If you are at the top of the callstack you *do* get a special
obligation, to log or whatnot, since the exception would otherwise pass
out of history.
This can be accomplished without writing any exception handling code by
borrowing the Resource Initlializing is Acquisition (RIIA) idiom from
C++, which is somewhat easy to implement in C# 2.0, as can be seen from
this article: http://www.codeproject.com/csharp/ex...s_generics.asp
"finally" is also nice, when the cleanup code isn't reusable.

RIIA is a great idiom, and fits *so* nicely into the C# using-syntax.
You can (relatively) easily move repeated cleanup from "finally"-clauses
to RIAA/using:

class SuspendUpdate: IDisposable {
readonly Control control;
public SuspendUpdate(C ontrol control) {
this.control = control;
control.Suspend Layout();
}
public void Dispose() { control.ResumeL ayOut(); }
public ~SuspendUpdate( ) {
throw new InvalidProgram(
string.Format(" Forgot to Dispose {0}", this.GetType(). FullName));
}
}
I would also like to add that I don't believe that catching exceptions
just to wrap them in custom exceptions and them rethrow them is a good
My opinion exactly. wrapping is evil, for one thing it destroys the
possibility to "catch-by-type".

The only catch/rethrow I do is when (usually due to rather poor design)
a subcomponent has to iterate through several operations:

IDictionary exceptions = new Hashtable();
foreach ( Foo foo in container )
try {
foo.f();
} catch ( Exception e) {
exceptions.Add( foo, e);
}
}
if ( exceptions.GetE numerator().Mov eNext() )
throw new SomeOperationsF ailed(exception s);

I prefer doing a callback in this situation, but somethimes the
interface is locked down due to years of use by customers.
idea. Same for logging excpetions, which should be done in one place
and one place only for the whole program.


Well,... yes -- but sometimes components wish to keep separate logs of
unexpected errors, for example to prove that it's the caller that's
doing things wrong. That's when:

try {
f();
} catch ( Exception e ) {
Log(e);
throw; // notice: rethrow!
}

comes in handy.

--
Helge Jensen
mailto:he****** ****@slog.dk
sip:he********* *@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-
Nov 17 '05 #15
Kevin Yu wrote:
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.
None of these things are good behaviour in C++ either :)

BTW: The default operator new should throw on out-of-memory errors, you
need to use "new(nothro w) Foo(...)" to get a null-pointer.
anyway, is it a good idea to wrap everything inside a try catch block, I
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
in try catch, I mean hack, this will make the system *Robus*.
Getting a bit on the sarcastic side, aren't you :)
enlighten me.


C++ doesn't have finally, so unless you RIAA you get:

Transaction t = Transaction(... );
try {
t.foo();
} catch ( ... ) {
t.Rollback();
throw;
}
t.Commit();

Which is ok in my book. (I would prefer RIAA on Transaction, but if it's
only in a few places...)

--
Helge Jensen
mailto:he****** ****@slog.dk
sip:he********* *@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-
Nov 17 '05 #16
As an example of how overblown the issue of the performance penalty for
exceptions is, on another group a while ago someone was asking whether
or not his application was suffering because it was throwing a couple
of hundred exceptions per *hour*. Many people said that yes, this was
probably slowing his application down significantly.


Hehe :-)

--
Miha Markic [MVP C#] - RightHand .NET consulting & development
www.rthand.com
SLODUG - Slovene Developer Users Group www.codezone-si.info
Nov 17 '05 #17
hi All

After all these discussions, I only have couple of questions here.

1. is it a good idea to wrap everything in try catch block? explain in
evidence/examples please.

2. is throwing exception in a try catch block a good idea? can Goto be an
alternative??

3. is rethrowing an exception a good design pattern or necessary? I mean
instead of returning a boolean

Kevin
"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??

Nov 17 '05 #18
"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 #19
"Kevin Yu" <ko**@hotmail.c om> wrote in message
news:On******** ******@TK2MSFTN GP09.phx.gbl...
hi All

After all these discussions, I only have couple of questions here.

1. is it a good idea to wrap everything in try catch block? explain in
evidence/examples please.
Yes and no. It's a very good idea to have a try/catch at the very top of
your program so that you can properly record exceptions. You actually get
this without writing any code, if an exception bubbles all they way up the
last chance exception handler shows you the call stack and exception and the
program exits. If that's acceptable, you don't have to do anything. If you
want to do something else, like write the exception to a log, use a single
try/catch at the top of your program.

After that, don't add a try/catch/finally unless you have a reason to.

2. is throwing exception in a try catch block a good idea? can Goto be an
alternative??
Yes, if you have an exception the best way to report it is to throw an
exception. I don't see how goto would be useful for reporting an
exceptional condition.

3. is rethrowing an exception a good design pattern or necessary? I mean
instead of returning a boolean
There's no one right answer. First, don't catch the exception unless you
have a reason. If you're just rethrowing it, then it's a waste. There are
plenty of cases where you can catch an exception and return true or false
but those would be expected exceptions (FormatExceptio ns etc). In general,
you want to rethrow the exception because it contains a lot of information
that will help you solve the problem. You don't want to get into a
situation where all of your methods return true or false to indicate an
error and you call GetLastExceptio n to find out what the error was.


Kevin
"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??


Nov 17 '05 #20

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

Similar topics

2
2174
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
1518
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
7308
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
1673
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
2014
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
4054
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
4601
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
13950
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
1737
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
9892
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
10997
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
10661
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
10718
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10347
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7889
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
5731
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4542
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
3
3172
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.