473,748 Members | 2,690 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 #1
40 13522
Compared to an "if" statement, yes, very bad.

Nov 17 '05 #2
Compare to anything it's bad.

hope my collage read this.
Kevin
"Mohammad" <m@abdulfatah.n et> wrote in message
news:11******** **************@ l41g2000cwc.goo glegroups.com.. .
Compared to an "if" statement, yes, very bad.

Nov 17 '05 #3
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 #4
Kevin Yu wrote:
is it a bad programming design to throw exception in the try block then
catch it??


Here are some guidelines that i have formulated after having tried
different strategies of exceptions:

Don't use exceptions to indicate errors you expect to occur.

Don't throw exceptions to "break" the program flow to a specific
catch-handler (goto):

try {
...
if ( unexpectedSitua tion )
throw new UnexpectedSitua tion();
...
} catch ( UnexpectedSitua tion ) {
// this is a complicated way to do goto
}

But if an unhandled exceptional situation occurs, then do what you would
normally do, for eample:

Stream s = new Stream("x");
try {
byte[] data = new byte[4];
int read = 0;
while ( read < data.Length ) {
int r = s.Read(data, read, data.Length - read);
if ( r == 0 )
throw new ParseError("Str eam ended before data could be read");
}
return data;
} catch ( InvalidOperatio nError ) { // unrelated to ParseError
// Reading failed!
} finally {
s.Close();
}

NOTE: you could use: "using (Stream s = new Stream("x")) { ... }"
instead of try/catch.

It is often good to write the code to have minimal try/catch-blocks, for
example if there is a risk that dict[key] may not be a Foo:

Foo foo = (Foo)dict[key];
try {
foo.f(...);
} catch ( FooProcessingEx ception ) {
... // sensible error handler
}

instead of:

try {
((Foo)dict[key]).f(...);
} catch ( FooProcessingEx ception ) {
... // sensible error handler
}

So that error-handling is narrowly applied to the code that is expected
to expose the error.

In general: only catch if you can actually do anyting to remedy the
error, or is at the top of the call-stack. A possible exception is
catching for logging and retrow:

try {
f(...);
catch ( Exception e ) {
Log(e);
throw;
}

--
Helge Jensen
mailto:he****** ****@slog.dk
sip:he********* *@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-
Nov 17 '05 #5
"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 #6
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. The only case that comes to mind where
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.

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.

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

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
idea. Same for logging excpetions, which should be done in one place
and one place only for the whole program.

Nov 17 '05 #7
I have posted another thead earlier on the code I am reading, I can see it's
clearly the guy is from a C++ backgroup, he basically try and catching
everything including the integer assignment, so I think he's abusing the try
catch statement, but I can't report to the police. so I asked the question
on the newsgroup, I got different opinions of the try catch block, I mean if
there is an exception, yea, for sure I want to catch it, but if wrapping
everything in the try catch block is the way to go?

I mean how much confidence you need for .NET?

any inside??
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 #8
Helge
he did the exactly same thing on all the code, I guess that's his fabulous
design.
try {
...
if ( unexpectedSitua tion )
throw new UnexpectedSitua tion();
...
} catch ( UnexpectedSitua tion ) {
// this is a complicated way to do goto
}

"Helge Jensen" <he**********@s log.dk> wrote in message
news:42******** ******@slog.dk. ..
Kevin Yu wrote:
is it a bad programming design to throw exception in the try block then
catch it??


Here are some guidelines that i have formulated after having tried
different strategies of exceptions:

Don't use exceptions to indicate errors you expect to occur.

Don't throw exceptions to "break" the program flow to a specific
catch-handler (goto):

try {
...
if ( unexpectedSitua tion )
throw new UnexpectedSitua tion();
...
} catch ( UnexpectedSitua tion ) {
// this is a complicated way to do goto
}

But if an unhandled exceptional situation occurs, then do what you would
normally do, for eample:

Stream s = new Stream("x");
try {
byte[] data = new byte[4];
int read = 0;
while ( read < data.Length ) {
int r = s.Read(data, read, data.Length - read);
if ( r == 0 )
throw new ParseError("Str eam ended before data could be read");
}
return data;
} catch ( InvalidOperatio nError ) { // unrelated to ParseError
// Reading failed!
} finally {
s.Close();
}

NOTE: you could use: "using (Stream s = new Stream("x")) { ... }"
instead of try/catch.

It is often good to write the code to have minimal try/catch-blocks, for
example if there is a risk that dict[key] may not be a Foo:

Foo foo = (Foo)dict[key];
try {
foo.f(...);
} catch ( FooProcessingEx ception ) {
... // sensible error handler
}

instead of:

try {
((Foo)dict[key]).f(...);
} catch ( FooProcessingEx ception ) {
... // sensible error handler
}

So that error-handling is narrowly applied to the code that is expected
to expose the error.

In general: only catch if you can actually do anyting to remedy the
error, or is at the top of the call-stack. A possible exception is
catching for logging and retrow:

try {
f(...);
catch ( Exception e ) {
Log(e);
throw;
}

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

Nov 17 '05 #9
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
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*.

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 #10

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

Similar topics

2
2168
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
1514
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
7279
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
1668
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
2007
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
4041
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
4595
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
13942
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
1715
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
8832
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9561
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
9381
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...
0
8252
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6078
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
4608
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
3316
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
2791
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2217
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.