473,805 Members | 2,137 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

too many Try/Catch blocks in code. Is there a better way?

Hello, I come from the VB6 world where we'd put a single ON ERROR GOTO
ErrHandler at the top of a method. Now whenever an error happened it
would drop into the ErrHandler code. In .Net it seems like you have
too many Try/Catch statements all throughout the code. I think this
is ugly error handling.

Is there a better way to handle exceptions in .Net 2.0 + then putting
all these Try/Catch blocks around code?

G
Oct 28 '08 #1
9 2811
"GiJeet" <gi****@yahoo.c omwrote in message
news:fe******** *************** ***********@p59 g2000hsd.google groups.com...
Hello, I come from the VB6 world where we'd put a single ON ERROR GOTO
ErrHandler at the top of a method. Now whenever an error happened it
would drop into the ErrHandler code. In .Net it seems like you have
too many Try/Catch statements all throughout the code. I think this
is ugly error handling.

Is there a better way to handle exceptions in .Net 2.0 + then putting
all these Try/Catch blocks around code?
Not quite sure why you would get loads of Try Catches

In VB6:-

Function DoSomething() As Long

On Error Goto An_Error

'Code here

The_Exit:

'Tidy up
Exit Function

An_Error:

'Handle error
'optionally
Resume The_Exit
'or re-raise error not handled
' Duplicated Tidy up code
Err.Raise num, source, description

End Function
In C#:-

int DoSomething()
{
try
{
//code here
}
catch(SpecialEx ception e) //optional
{
//code to handle special exception
}
catch(Exception e) //(Exception e) can be deleted it e not used
{
//code to handle general exception
}
finally
{
//Tidy up; this always runs.
}
}

The point is there is no need for multiple Try/Catch blocks any more than
there is a need for multiple On Error Resume Handler lines in a VB6
procedure.
--
Anthony Jones - MVP ASP/ASP.NET

Oct 28 '08 #2
"GiJeet" <gi****@yahoo.c omwrote in message
news:fe******** *************** ***********@p59 g2000hsd.google groups.com...
Hello, I come from the VB6 world where we'd put a single ON ERROR GOTO
ErrHandler at the top of a method. Now whenever an error happened it
would drop into the ErrHandler code. In .Net it seems like you have
too many Try/Catch statements all throughout the code. I think this
is ugly error handling.
I, too, am a seasoned VB6 programmer, and I think that try/catch is far more
elegant than what VB did. What makes it look "ugly" to you is that error
handling in VB was basically a hack that you've gotten used to. It's time to
get used to something else.
Is there a better way to handle exceptions in .Net 2.0 + then putting
all these Try/Catch blocks around code?
No. That's the way. Get used to it. Seriously. Anything else would be
beating your head against a wall.
Oct 28 '08 #3
GiJeet wrote:
Hello, I come from the VB6 world where we'd put a single ON ERROR GOTO
ErrHandler at the top of a method. Now whenever an error happened it
would drop into the ErrHandler code. In .Net it seems like you have
too many Try/Catch statements all throughout the code. I think this
is ugly error handling.

Is there a better way to handle exceptions in .Net 2.0 + then putting
all these Try/Catch blocks around code?

G
You could use the same catch-anything approach as in VB6, and use a
try..catch around all the code in the method, but that is not a good way
of handing exceptions. Just as the error handing in VB6 isn't very good
either.

You should only catch exceptions where you anticipate them, and you
should specify the exception type(s) that the code could normally throw.
If you catch an exception in your code that you don't know how to
handle, there is no point in catching it at that level. You should catch
that at the application level instead.

Handling exceptions correctly is a bit of work, but that is one of the
things that gives stability to the application.

--
Göran Andersson
_____
http://www.guffa.com
Oct 28 '08 #4
http://sholliday.space s.live.com/Blog/cns!A68482B9628 A842A!234.entry
You should find the Krzysztof Cwalina article and bookmark it.

You should also (via Brad Abram advice) write alot more try/finally

try
{

}
// an intentional lack of a "catch" here
finally
{

}

blocks (like above), rather than try/catch/finally blocks.
Allowing the exception to bubble up is usually a good default....unle ss you
have a specific reason to not do so.

..............


"GiJeet" <gi****@yahoo.c omwrote in message
news:fe******** *************** ***********@p59 g2000hsd.google groups.com...
Hello, I come from the VB6 world where we'd put a single ON ERROR GOTO
ErrHandler at the top of a method. Now whenever an error happened it
would drop into the ErrHandler code. In .Net it seems like you have
too many Try/Catch statements all throughout the code. I think this
is ugly error handling.

Is there a better way to handle exceptions in .Net 2.0 + then putting
all these Try/Catch blocks around code?

G

Oct 28 '08 #5
"MC" <fo************ **@www.ai.uga.e du.slash.mcwrot e in message
news:ez******** *****@TK2MSFTNG P03.phx.gbl...
The advantage of try/catch is that different parts of your program can
have
different error handlers. If you want the equivalent of "ON ERROR GOTO,"
put a single try/catch block around Application.Run (...) in the main
program.
(Or around the whole of whatever routine you want to protect.)
To be fair, VB could do the same thing. You could have On Error GoTo
ErrorHandler1 and later in the same procedure On Error GoTo ErrorHandler2.
It's just that most people didn't create multiple error handlers; they just
wrote one big one with a Select Case statement to examine the error number.
The real problem is that the error blocks weren't "directly connected" to
the statements that might fail; you had to jump into (goto) the error block
and then jump (resume) back.
Oct 28 '08 #6
In many Cases
there is a Top Method calling the lower classes and methods

if you get a non recoverable error
1. What are you gonna do....nothing crash , log it etc

if you had a App Error Block (try/catch) at top of ur application
let it throw up to that

there are lots of specific places i will use try catch because i need to
catch the error where it took place
but many times , does not really matter if it just throws all the way up to
the top
log it, or do what you do with it

"GiJeet" <gi****@yahoo.c omwrote in message
news:fe******** *************** ***********@p59 g2000hsd.google groups.com...
Hello, I come from the VB6 world where we'd put a single ON ERROR GOTO
ErrHandler at the top of a method. Now whenever an error happened it
would drop into the ErrHandler code. In .Net it seems like you have
too many Try/Catch statements all throughout the code. I think this
is ugly error handling.

Is there a better way to handle exceptions in .Net 2.0 + then putting
all these Try/Catch blocks around code?

G

Oct 28 '08 #7
"Jeff Johnson" <i.***@enough.s pamwrote in message
news:eN******** ******@TK2MSFTN GP06.phx.gbl...
"MC" <fo************ **@www.ai.uga.e du.slash.mcwrot e in message
news:ez******** *****@TK2MSFTNG P03.phx.gbl...
>The advantage of try/catch is that different parts of your program can
have
different error handlers. If you want the equivalent of "ON ERROR GOTO,"
put a single try/catch block around Application.Run (...) in the main
program.
(Or around the whole of whatever routine you want to protect.)

To be fair, VB could do the same thing. You could have On Error GoTo
ErrorHandler1 and later in the same procedure On Error GoTo ErrorHandler2.
It's just that most people didn't create multiple error handlers; they
just wrote one big one with a Select Case statement to examine the error
number. The real problem is that the error blocks weren't "directly
connected" to the statements that might fail; you had to jump into (goto)
the error block and then jump (resume) back.
In most of those case though it would be clear that an extract function
refactor would be needed. As soon as you needed more than one On Error Goto
in a procedure it should immediately trigger that refactor.

--
Anthony Jones - MVP ASP/ASP.NET

Oct 28 '08 #8
"sloan" <sl***@ipass.ne twrote in message
news:Oy******** ******@TK2MSFTN GP02.phx.gbl...
http://sholliday.space s.live.com/Blog/cns!A68482B9628 A842A!234.entry
You should find the Krzysztof Cwalina article and bookmark it.

You should also (via Brad Abram advice) write alot more try/finally

try
{

}
// an intentional lack of a "catch" here
finally
{

}

blocks (like above), rather than try/catch/finally blocks.
Allowing the exception to bubble up is usually a good default....unle ss
you have a specific reason to not do so.
In many of such cases though the task to be performed in the finally is one
or more Dispose calls. In which case C#'s using() { } construct is better.
--
Anthony Jones - MVP ASP/ASP.NET

Oct 28 '08 #9
//
>
In many of such cases though the task to be performed in the finally is
one or more Dispose calls. In which case C#'s using() { } construct is
better.
//

I second that!

.........

"Anthony Jones" <An***********@ yadayadayada.co mwrote in message
news:u3******** ******@TK2MSFTN GP05.phx.gbl...
"sloan" <sl***@ipass.ne twrote in message
news:Oy******** ******@TK2MSFTN GP02.phx.gbl...
>http://sholliday.space s.live.com/Blog/cns!A68482B9628 A842A!234.entry
You should find the Krzysztof Cwalina article and bookmark it.

You should also (via Brad Abram advice) write alot more try/finally

try
{

}
// an intentional lack of a "catch" here
finally
{

}

blocks (like above), rather than try/catch/finally blocks.
Allowing the exception to bubble up is usually a good default....unle ss
you have a specific reason to not do so.

In many of such cases though the task to be performed in the finally is
one or more Dispose calls. In which case C#'s using() { } construct is
better.
--
Anthony Jones - MVP ASP/ASP.NET

Oct 28 '08 #10

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

Similar topics

6
552
by: Erik Cruz | last post by:
Hi. I have read several articles recommending avoid to raise exceptions when possible, since exceptions are expensive to the system. Removing code from Try... Catch blocks can help performance? The following 2 first lines of code - I think - can't raise exceptions: Try Dim str As String Dim intVar As Integer
11
6897
by: kaeli | last post by:
Hey all, I'd like to start using the try/catch construct in some scripts. Older browsers don't support this. What's the best way to test for support for this construct so it doesn't kill non-supporting browsers? TIA -- --
6
2776
by: ChrisB | last post by:
Hello All: I notice that when using try/catch blocks in C#, variables declared in the try block go out of scope in the finally block. So, for example, the following code generates a compiler error: try { SqlDataReader sqlDataReader = new SqlDataReader(sqlConnection,
8
2738
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? (ie, forget the finally block and just end the try/catch and put the code after the try/catch block). Or does the "finally" construct add some additional functionality?
11
3494
by: Pohihihi | last post by:
I was wondering what is the ill effect of using try catch in the code, both nested and simple big one. e.g. try { \\ whole app code goes here } catch (Exception ee) {}
22
3378
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 why. Is this true? If so, why? Thanks. STom
32
6132
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 understand Finally runs whether an error was caught or not, I haven't found a use for finally yet.
5
3115
by: not_a_commie | last post by:
Using a synchronized Queue, I did some testing on catching the "queue was empty on dequeue" exception vs. doing my own lock, checking for empty, and then dequeuing. The try/catch method, though simpler in code, was 100x slower than doing my own empty-check before dequeue. That seems incredible to me that the try/catch handlers could be that much slower than a lock and an empty check. It makes me want to go through the codebase and rip out...
0
10613
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...
1
10368
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,...
1
7649
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
6876
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
5544
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...
0
5678
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4327
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
3846
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3008
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.