473,785 Members | 2,209 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

try-catch - but a catch which catches everything

Hi,

I have something like this:

try
{
// some code
}
catch // note - i am catching everything now
{
// do something
}

Will this sort of catch statement, catch 'unsafe' and 'kernal-level'
exceptions (even if the app is a simple asp.net app with no unsafe stuff)?
(just wanted to confirm as I had a debate with one of my friends - AFAIK i
feel it doesn't since no unsafe code is used and since Win32 exceptions are
mapped into managed .NET exception classes)
Also, in many cases, i have catch blocks which does nothing - because i
don't want any exception to be propagated...so mething like follows.

public bool IsInteger(strin g val)
{
bool result;

try
{
int.Parse(val);
result = true;
}
catch
{
result = false;
}
return result;
}

Is this OK (a good practice)?

Thanks,
Benny

Nov 17 '05
13 3724

"Bruce Wood" <br*******@cana da.com> wrote in message
news:11******** **************@ f14g2000cwb.goo glegroups.com.. .
You should "never" have a catch-all like this: neither "catch" by
itself nor "catch (Exception ex)".


Never say "never".

try
{
ModifyDB();
Commit();
}
catch
{
Rollbac();
throw;
}

Perhaps you don't consider this "catching" the exception since it is always
re-thrown?

Also, when processing a large list of items (e.g. reading millions of
records from a file) there are a myriad of things that can go wrong. Your
catch list would stretch for miles. However, you certainly don't want the
whole process to stop 90% of the way through because one record had an
error, do you? Log the exception, go on to the next item, deal with the
exception when the process has finished.
Nov 17 '05 #11
Ah, yes. Point taken. I hadn't considered the rollback case.

Squirreling away the exception and dealing with it later is another
valid reason to "catch all" exceptions. Point taken, again. :-)

Nov 17 '05 #12
Hi Benny,

try
{
// some code
}
catch // note - i am catching everything now
{
// do something
}


As others have pointed out, this is universally regarded as bad practice,
except in a small number of very specific situations. It is one of those
things, like "goto's" that you can just take on authority.

Still, I'll give you an real-world example of why...

Some months ago, in a test utility, I had to introduce an exception handler.
Because it was just test code, I decided to do a "quick and dirty", as in
your example..

try
{
// some code
}
catch
{
// do something
}

Last week, I shifted to Visual Studio 2005, and my test utility stopped
working. I *eventually* found the reason. My code had, all along, an
underlying thread flaw. .Net CLR 2.0 detects this flaw, and raises an
exception. The exception happened to be caught in the catch-all, and the
symptoms of the problem arose later. If i didn't have the catch all, then the
exception would have gone straight to top, and halted the program
immediately, with a meaningful diagnostic.

My "quick and dirty" in the test utility ended up costing me some time. If
it had been complex production code, which I had inherited from someone else,
it could have been more serious, and could have cost a *lot* more time.

Regards,

Javaman
Nov 17 '05 #13
Hi Benny,

You can implement the IsInteger routine without try/catch in .Net 1.1 using
the double.TryParse static method that has already been mentioned. It has a
parameter NumberStyles which you call with Integer, and is equivalent in
result to your previous method.

public static bool IsInteger(strin g s)
{
double result;
return double.TryParse (s, System.Globaliz ation.NumberSty les.Integer, null,
out result);
}

Its a bit cryptic though that you have to use a method of double.

Hope this helps.

Regards,
Phil

"Benny" wrote:
Hi,

I have something like this:

try
{
// some code
}
catch // note - i am catching everything now
{
// do something
}

Will this sort of catch statement, catch 'unsafe' and 'kernal-level'
exceptions (even if the app is a simple asp.net app with no unsafe stuff)?
(just wanted to confirm as I had a debate with one of my friends - AFAIK i
feel it doesn't since no unsafe code is used and since Win32 exceptions are
mapped into managed .NET exception classes)
Also, in many cases, i have catch blocks which does nothing - because i
don't want any exception to be propagated...so mething like follows.

public bool IsInteger(strin g val)
{
bool result;

try
{
int.Parse(val);
result = true;
}
catch
{
result = false;
}
return result;
}

Is this OK (a good practice)?

Thanks,
Benny

Nov 17 '05 #14

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

Similar topics

39
6072
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 containing norwegian special characters æ, ø and å. >>> liste =
13
11976
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: print "What is the answer?" finally: print 42
7
9743
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: > > try: > x = could_raise_an_exception(23) > process(x) > except Exception, err: > deal_with_exception(err)
9
3829
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 to catch the exception and still have a finally block? This is a fictional example of what I want....
26
2522
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 Error # Error is subclass of Exception
6
3385
by: William Park | last post by:
(crossposted to comp.lang.python, because this may be of interest to them.) Python has try-block, within which you can raise exception. Once it's raised, execution breaks out of the try-block and is caught at the end of try-block. Now, Bash has similiar feature. I've added try-block and 'raise' builtin into Bash-3.0. Typical usage would go something like try
1
1768
by: djw | last post by:
c.l.p- I am having trouble understanding how one is supposed to correctly utilize try:...except:...finally: in real code. If I have a block of code like: def foo(): try: ... some code that can raise an exception ...
40
3046
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 goodness of Python whenever I talk with fellow developers, but I always hit a snag when it comes to discussing the finer points of the execution model (specifically, exceptions). Without fail, when I start talking with some of the "old-timers"...
4
2467
by: wk6pack | last post by:
Hi, I was wondering why when I declare the dim variable outside the try statement, I could use the .dispose() function but when I declare it inside the try statement, I get Name 'varname' is not declared. thanks, Will
20
3927
by: John Salerno | last post by:
I'm starting out with this: try: if int(text) 0: return True else: self.error_message() return False except ValueError: self.error_message()
0
9646
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
9483
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
10346
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
10157
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
10096
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
8982
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
6742
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
5514
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2887
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.