473,419 Members | 1,565 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,419 software developers and data experts.

Is try-catch block a way to prevent a crash?

Hi,

I've found that if I wrap my code with a try-catch block in the
fashion illustrated below, it'll do what is specified in the catch
section instead of crashing. Could anyone confirm that this is true?

If it's true, I'll modify every single method in my program to wrap it
with a try-catch block to prevent it from crashing.

FYI, the try-catch block I mentioned is as below:

void SomeMethod()
{
try
{
// Do something

}
catch (Exception e)
{
logger.Write (e.Message);
}

}
Jun 27 '08 #1
10 1850
On Thu, 12 Jun 2008 19:12:36 -0700 (PDT), Curious
<fi********@yahoo.comwrote:
>Hi,

I've found that if I wrap my code with a try-catch block in the
fashion illustrated below, it'll do what is specified in the catch
section instead of crashing. Could anyone confirm that this is true?

If it's true, I'll modify every single method in my program to wrap it
with a try-catch block to prevent it from crashing.

FYI, the try-catch block I mentioned is as below:

void SomeMethod()
{
try
{
// Do something

}
catch (Exception e)
{
logger.Write (e.Message);
}

}
Yes, that is what Try/Catch does.

However, wrapping every single method like that is probably a really
bad idea. What if the caller of the method expects the method to do
something, what will happen when it either doesn't do anything, or
maybe worse, does half of it.
Jun 27 '08 #2
Hi Jack,

I get the idea. I'll look at each method carefully to make sure they
do what they're supposed to.

I'll wrap the methods with a try-catch block to prevent any crash.
Jun 27 '08 #3
On Jun 13, 8:32*am, Curious <fir5tsi...@yahoo.comwrote:
Hi Jack,

I get the idea. I'll look at each method carefully to make sure they
do what they're supposed to.

I'll wrap the methods with a try-catch block to prevent any crash.
You should really read this first:

http://msdn.microsoft.com/en-us/libr...exception.aspx

Marc
http://nomagichere.blogspot.com
Jun 27 '08 #4
Curious <fi********@yahoo.comwrote:
I get the idea. I'll look at each method carefully to make sure they
do what they're supposed to.

I'll wrap the methods with a try-catch block to prevent any crash.
No, please don't. It doesn't mean your code will work better - it just
means it will fail fairly silently and keep going *in error
conditions*.

When an exception happens, most of the time the calling code won't be
able to sensibly recover and complete the operation. For instance, if
you're trying to return a web page and something goes wrong, your best
course of action will be to display an error page - not plough on
regardless of the error.

Error handlers are usually at the top level of the application, or in
*very* specific circumstances where you can actually work round the
error (or retry, etc).

Wrapping every method in try/catch is a recipe for disaster, as well as
making your code much harder to understand.

--
Jon Skeet - <sk***@pobox.com>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Jun 27 '08 #5
Curious wrote:

I get the idea. I'll look at each method carefully to make sure they
do what they're supposed to.

I'll wrap the methods with a try-catch block to prevent any crash.
Some exceptions will not lead to a crash, this can be even worse. For
example, when an exception occurs in BackgroundWorker(DoWork event) - it
behaves as though happened nothing. So the application logic fails,
without a visible hint.

How to catch Exception in Background Worker
http://devintelligence.com/blogs/net...7/17/1096.aspx
Another hint: AppDomain.CurrentDomain.UnhandledException will not catch
Exceptions in WPF applications. WPF requires a different way to catch
unhandled exceptions, using app.DispatcherUnhandledException
Maybe there are even more pitfalls in the Framework...
Hope this Helps(tm)
--
Michael Justin
SCJP, SCJA
betasoft - Software for Delphiâ„¢ and for the Javaâ„¢ platform
http://www.mikejustin.com - http://www.betabeans.de
Jun 27 '08 #6
Yes, --every-- will also impose significant performance impacts I
understand. In your opinion Jon which circumstances have motivated you to
draw that fine line when and where try-catch-finally is best used and how to
elegantly respond? And how do you use finally to its best advantage?

"Jon Skeet [C# MVP]" <sk***@pobox.comwrote in message
news:MP*********************@msnews.microsoft.com. ..
Curious <fi********@yahoo.comwrote:
>I get the idea. I'll look at each method carefully to make sure they
do what they're supposed to.

I'll wrap the methods with a try-catch block to prevent any crash.

No, please don't. It doesn't mean your code will work better - it just
means it will fail fairly silently and keep going *in error
conditions*.

When an exception happens, most of the time the calling code won't be
able to sensibly recover and complete the operation. For instance, if
you're trying to return a web page and something goes wrong, your best
course of action will be to display an error page - not plough on
regardless of the error.

Error handlers are usually at the top level of the application, or in
*very* specific circumstances where you can actually work round the
error (or retry, etc).

Wrapping every method in try/catch is a recipe for disaster, as well as
making your code much harder to understand.

--
Jon Skeet - <sk***@pobox.com>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Jun 27 '08 #7
clintonG <no****@nowhere.comwrote:
Yes, --every-- will also impose significant performance impacts I
understand.
Well, possibly. It limits what the JIT compiler can do, but the actual
wrapping with try/catch doesn't cost anything. There's cost to catching
an exception just to rethrow it, however.
In your opinion Jon which circumstances have motivated you to
draw that fine line when and where try-catch-finally is best used and how to
elegantly respond? And how do you use finally to its best advantage?
My "finally" blocks are almost always invisible due to the "using"
statement.

I rarely write "catch" blocks unless either:
a) I'm at some notional "top level" where it's appropriate to
log/report the error
b) I know about the error in advance and can handle it (but not avoid
it in the first place)
c) I wish to catch and wrap it

--
Jon Skeet - <sk***@pobox.com>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Jun 27 '08 #8
After reading your posts, I feel it's very difficult to handle
exceptions. Since my code is so complicated, I don't know what to do
to handle so many possibilities of exceptions.

I post a simple method here, could anyone kindly show me how to handle
exception in this piece of code?

void ReadBearTable()
{
try
{
StreamReader sr = new StreamReader(new FileStream("C:\
\Temp\\Bear.tkr", FileMode.Open, FileAccess.Read));
string line = sr.ReadLine();

while (line != null)
{
mBearList.Add(line);

line = sr.ReadLine();
}

sr.Close();
}
catch (Exception e)
{
logger.LogMessageBarMessage(ESeverity.Error,
e.Message);
}
}
Jun 27 '08 #9
Ummmmm .... You've handled it!
"Curious" <fi********@yahoo.comwrote in message
news:04**********************************@34g2000h sh.googlegroups.com...
After reading your posts, I feel it's very difficult to handle
exceptions. Since my code is so complicated, I don't know what to do
to handle so many possibilities of exceptions.

I post a simple method here, could anyone kindly show me how to handle
exception in this piece of code?

void ReadBearTable()
{
try
{
StreamReader sr = new StreamReader(new FileStream("C:\
\Temp\\Bear.tkr", FileMode.Open, FileAccess.Read));
string line = sr.ReadLine();

while (line != null)
{
mBearList.Add(line);

line = sr.ReadLine();
}

sr.Close();
}
catch (Exception e)
{
logger.LogMessageBarMessage(ESeverity.Error,
e.Message);
}
}
Jun 27 '08 #10
Curious <fi********@yahoo.comwrote:
After reading your posts, I feel it's very difficult to handle
exceptions. Since my code is so complicated, I don't know what to do
to handle so many possibilities of exceptions.
The fundamental question is: how serious is the problem? Can you
continue?
I post a simple method here, could anyone kindly show me how to handle
exception in this piece of code?
Well, why are you catching it here? Are you happy that any caller who
calls your ReadBearTable method won't know whether or not it's
completed successfully? Or is it likely to be a critical error which
really means your program can't continue? Should you let the caller
decide instead of you just swallowing the exception?

--
Jon Skeet - <sk***@pobox.com>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Jun 27 '08 #11

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

Similar topics

39
by: Erlend Fuglum | last post by:
Hi everyone, I'm having some trouble sorting lists. I suspect this might have something to do with locale settings and/or character encoding/unicode. Consider the following example, text...
13
by: KefX | last post by:
This may have been discussed before, but I'm kind of confused as to why Python doesn't support having both an except ~and~ a finally clause, like this: try: raise RuntimeException except:...
7
by: Robert Brewer | last post by:
Alex Martelli wrote in another thread: > One sign that somebody has moved from "Python newbie" to "good Python > programmer" is exactly the moment they realize why it's wrong to code: > > ...
9
by: David Stockwell | last post by:
In referring to my copy of the python bible, it tells me I can't use all three items 'try' except and finally. I can use the t/f or t/e combinations though What combination can i use if i want...
26
by: djw | last post by:
Hi, Folks- I have a question regarding the "proper" use of try: finally:... Consider some code like this: d = Device.open() try: d.someMethodThatCanRaiseError(...) if SomeCondition: raise...
3
by: Steven Bethard | last post by:
So I have code that looks something like this: def f(xs): for x in xs: y = g(x) # can raise exception AnException for z in h(y): k(z) # can raise a variety of exceptions Now, if g(x) raises...
40
by: Steve Juranich | last post by:
I know that this topic has the potential for blowing up in my face, but I can't help asking. I've been using Python since 1.5.1, so I'm not what you'd call a "n00b". I dutifully evangelize on the...
3
by: Sori Schwimmer | last post by:
Hi, I think that would be useful to have an improved version of the "try" statement, as follows: try(retrys=0,timeout=0): # things to try except: # what to do if failed
4
by: John Salerno | last post by:
My code is below. The main focus would be on the OnStart method. I want to make sure that a positive integer is entered in the input box. At first I tried an if/else clause, then switched to...
5
by: Fabio Z Tessitore | last post by:
Hi all, reading Dive Into Python, on Chapter 6 (exception), I've found: "This code comes from the getpass module, a wrapper module for getting a password from the user" try: import...
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: 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...
0
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...
0
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...
1
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...
0
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...
0
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,...

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.