Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.java.programmer > #12858 > unrolled thread

Exception Handling

Started byNovice <novice@example..com>
First post2012-03-11 01:51 +0000
Last post2012-03-13 06:05 -0300
Articles 17 on this page of 37 — 8 participants

Back to article view | Back to comp.lang.java.programmer


Contents

  Exception Handling Novice <novice@example..com> - 2012-03-11 01:51 +0000
    Re: Exception Handling Lew <noone@lewscanon.com> - 2012-03-10 18:39 -0800
      Re: Exception Handling Arved Sandstrom <asandstrom3minus1@eastlink.ca> - 2012-03-11 11:53 -0300
        Re: Exception Handling Lew <noone@lewscanon.com> - 2012-03-11 10:51 -0700
          Re: Exception Handling Arved Sandstrom <asandstrom3minus1@eastlink.ca> - 2012-03-11 16:35 -0300
      Re: Exception Handling Novice <novice@example..com> - 2012-03-11 17:05 +0000
        Re: Exception Handling Lew <noone@lewscanon.com> - 2012-03-11 10:53 -0700
          Re: Exception Handling Novice <novice@example..com> - 2012-03-11 20:36 +0000
        Re: Exception Handling Lew <noone@lewscanon.com> - 2012-03-11 11:07 -0700
          Re: Exception Handling Arved Sandstrom <asandstrom3minus1@eastlink.ca> - 2012-03-11 17:00 -0300
            Re: Exception Handling Novice <novice@example..com> - 2012-03-11 22:02 +0000
          Re: Exception Handling Arivald <NOSPAMarivald@interia.pl> - 2012-03-11 21:03 +0100
            Re: Exception Handling Arved Sandstrom <asandstrom3minus1@eastlink.ca> - 2012-03-11 18:31 -0300
          Re: Exception Handling Novice <novice@example..com> - 2012-03-11 21:54 +0000
            Re: Exception Handling Patricia Shanahan <pats@acm.org> - 2012-03-11 15:26 -0700
              Re: Exception Handling Novice <novice@example..com> - 2012-03-11 23:23 +0000
                Re: Exception Handling Lew <noone@lewscanon.com> - 2012-03-11 16:52 -0700
                  Re: Exception Handling Novice <novice@example..com> - 2012-03-12 17:16 +0000
                    Re: Exception Handling Lew <noone@lewscanon.com> - 2012-03-13 08:31 -0700
                Re: Exception Handling Patricia Shanahan <pats@acm.org> - 2012-03-11 17:51 -0700
                  Re: Exception Handling Novice <novice@example..com> - 2012-03-12 17:26 +0000
              Re: Exception Handling Arne Vajhøj <arne@vajhoej.dk> - 2012-03-12 14:49 -0400
            Re: Exception Handling Arved Sandstrom <asandstrom3minus1@eastlink.ca> - 2012-03-11 20:46 -0300
              Re: Exception Handling Novice <novice@example..com> - 2012-03-12 17:43 +0000
        Re: Exception Handling Patricia Shanahan <pats@acm.org> - 2012-03-11 11:14 -0700
          Re: Exception Handling Novice <novice@example..com> - 2012-03-11 22:35 +0000
            Re: Exception Handling Lew <noone@lewscanon.com> - 2012-03-11 16:58 -0700
              Re: Exception Handling Novice <novice@example..com> - 2012-03-12 15:44 +0000
                Re: Exception Handling Gene Wirchenko <genew@ocis.net> - 2012-03-12 10:34 -0700
        Re: Exception Handling Arivald <NOSPAMarivald@interia.pl> - 2012-03-11 20:34 +0100
          Re: Exception Handling Novice <novice@example..com> - 2012-03-11 22:36 +0000
      Re: Exception Handling Arne Vajhøj <arne@vajhoej.dk> - 2012-03-12 14:41 -0400
    Re: Exception Handling Arne Vajhøj <arne@vajhoej.dk> - 2012-03-12 14:37 -0400
      Re: Exception Handling Novice <novice@example..com> - 2012-03-12 22:43 +0000
        Re: Exception Handling Lew <lewbloch@gmail.com> - 2012-03-12 16:11 -0700
        Re: Exception Handling Arivald <NOSPAMarivald@interia.pl> - 2012-03-13 00:54 +0100
          Re: Exception Handling Arved Sandstrom <asandstrom3minus1@eastlink.ca> - 2012-03-13 06:05 -0300

Page 2 of 2 — ← Prev page 1 [2]


#12902

FromNovice <novice@example..com>
Date2012-03-12 17:26 +0000
Message-ID<XnsA01488C1A3E11jpnasty@94.75.214.39>
In reply to#12893
Patricia Shanahan <pats@acm.org> wrote in 
news:QdidndGYsfwc1cDSnZ2dnUVZ_tKdnZ2d@earthlink.com:

> On 3/11/2012 4:23 PM, Novice wrote:
>> Patricia Shanahan<pats@acm.org>  wrote in
>> news:S7GdnRomTdoRu8DSnZ2dnUVZ_sWdnZ2d@earthlink.com:
>>
>>> On 3/11/2012 2:54 PM, Novice wrote:
>>>> Lew<noone@lewscanon.com>   wrote in news:jjipli$np7$1
>> @news.albasani.net:
>>> ...
>>>>> It is common and frequently useful to create an application-
specific
>>>>> checked exception. Again, and I've said this many times, think 
about
>>>>> what will be useful when troubleshooting a problem. Many times, a
>>>>> custom exception is useful. It says that the underlying exception 
has
>>>>> been caught, logged and wrapped.
>>>>>
>>>> But how is a custom FooException better than a good ol'
>>>> IllegalArgumentException? I'm not quite getting that yet.
>>>
>>> Generally, you should use different Exception subclasses for cases 
that
>>> may need different handling, so that callers can set up appropriate
>>> catch blocks.
>>>
>>> Regardless of the conditions under which you choose to generate
>>> IllegalArgumentException, many methods you will be calling use it to
>>> indicate an illegal argument condition that has not yet been logged 
or
>>> otherwise reported.
>>>
>>> If you also use it to indicate exceptions that have already been
>> logged,
>>> you risk either repeated logging of the same issue, or failure to 
log.
>>>
>>> On the other hand, if you create an Exception subclass that you only
>>> throw after logging the underlying problem, there is no ambiguity.
>>> Callers have to deal with the consequences of the failure, but should
>>> only generate log messages if they have something to add. The
>> underlying
>>> problem has already been logged.
>>>
>> I'm sure this will seem like good advice when I understand it but it's
>> still vague to me.
>>
>> It would really help if you could suggest a concrete example or two 
that
>> show when to use a custom exception and why it's better.
>>
> 
> Using the same exception for "illegal argument" and "already logged and
> wrapped" is unlikely to get you into much trouble in a short program
> viewed for a few minutes.
> 
> The potential trouble comes when you have a large program, too large to
> read the whole thing before making a change, and it is being modified 
by
> a programmer who does not know, or does not remember, that the 
exception
> has those two meanings.
> 
> That makes it difficult to illustrate in a small example.
> 
> Remember that a lot of what you are being told, both in the newsgroup
> and in the articles you are reading, is based on experience with
> maintaining large programs over many years.
> 

As I've replied to Lew, I see the difficulty in talking about this. There 
are so many different situations that come up that it's hard to be 
specific without saying something that is only valid for the specific 
situation but might be misleading if applied to the general situation.

I'm mostly focused on my little program and understanding what it should 
do. There is definitely a danger that I might over-generalize from the 
specifics of my case and use techniques that are appropriate for my 
situation in ways that are inappropriate to a very different program. 

You responders are thinking about lots of different programs, often much 
vaster than anything I'm doing, and generalizing to cover a lot of cases, 
some very different from mine.

There's no getting away from it. This is a tricky thing to communicate 
and learn. I'll just have to do my best to apply general principles to 
specific situations and stand ready to adjust my techniques as I get more 
experience with things. 

I look forward to the day when I have real code walkthroughs again. For 
now, I think I need to focus on principles and coding things that are at 
least fairly close to best practices but maintain the flexibility to 
tweak my code as necessary when I discover that it doesn't work well or 
fails to fit best practices used in the Java community.

Thanks, as always, for your thoughts on these matters, Patricia.

-- 
Novice

[toc] | [prev] | [next] | [standalone]


#12908

FromArne Vajhøj <arne@vajhoej.dk>
Date2012-03-12 14:49 -0400
Message-ID<4f5e453d$0$293$14726298@news.sunsite.dk>
In reply to#12883
On 3/11/2012 6:26 PM, Patricia Shanahan wrote:
> On 3/11/2012 2:54 PM, Novice wrote:
>> Lew<noone@lewscanon.com> wrote in news:jjipli$np7$1@news.albasani.net:
> ...
>>> It is common and frequently useful to create an application-specific
>>> checked exception. Again, and I've said this many times, think about
>>> what will be useful when troubleshooting a problem. Many times, a
>>> custom exception is useful. It says that the underlying exception has
>>> been caught, logged and wrapped.
>>>
>> But how is a custom FooException better than a good ol'
>> IllegalArgumentException? I'm not quite getting that yet.
>
> Generally, you should use different Exception subclasses for cases that
> may need different handling, so that callers can set up appropriate
> catch blocks.

I think the word *may* is critical here.

It is not just if one need to write two different catch blocks
within the next 10 minutes.

It is actually if it is reasonable likely that someone will want
to write two different catch blocks within the next 10 or 20 years.

Arne

[toc] | [prev] | [next] | [standalone]


#12890

FromArved Sandstrom <asandstrom3minus1@eastlink.ca>
Date2012-03-11 20:46 -0300
Message-ID<yPa7r.13504$wf.12231@newsfe09.iad>
In reply to#12878
On 12-03-11 06:54 PM, Novice wrote:
> Lew <noone@lewscanon.com> wrote in news:jjipli$np7$1@news.albasani.net:
> 
[ SNIP ]

>> We've discussed this before, remember?
>>
>> It's not expensive. When you're calling a logger statement for an
>> error, the cost of the error SWAMPS the time in the logger. Think
>> about it. 
>>
> I suppose I'm too easily swayed by other opinions. Arved, who seems very 
> knowledgeable, cited that article, which seemed to give it his seal of 
> approval. I don't know the author of the article but I tend to assume he 
> must be an expert to be asked to write about a Java topic. The author 
> cites people who he considers experts and the upshot is that the advice 
> seems to argue against putting positioning information in the log unless 
> its necessary (which it probably isn't if the stacktrace is in the log). 
> Now you make a persuasive argument contradicting the article. I'm 
> satisfied that you have serious expertise in this area so I have no 
> reason to dismiss your argument. But why didn't the experts who wrote the 
> article modify their remarks accordingly? 
[ SNIP ]

The article did have my "seal of approval". That's to say, I read the
article, and agreed with most of it. Not 100 percent, but most of it.
And I didn't see anything in it which would lead a person down the
garden path. I recommend it because it's a useful read...but you
shouldn't accept it as the gospel, just as you shouldn't accept
"Effective Java" as the gospel either.

Logging is also a somewhat subjective matter. That's why different
opinions on different specifics. Ultimately TIMTOWTDI, to borrow a Perl
motto. What really counts is when the rubber meets the road, and the
logs have to be _used_, did the ops support people get what they needed
out of the logs, without too much anguish?

You've heard different viewpoints - mine and others' - on including
positional informational in logs. In the final analysis what matters is
the sufficiency of information in the logs. Don't worry overmuch about
logging performance until it's a problem; the whole point of having
layouts in a properties file is that you can tweak them if necessary. I
have a specific reason why I don't normally include certain positional
information, except for error stacktraces, but someone else might have a
good reason for why they do want this info.

One note: *never* assume that because somebody has an article in a blog
or an Internet magazine or a dead tree magazine or even a scholarly
journal that they are experts. Check the references. Check the style of
the prose: are the conclusions backed up by understandable argument, or
are they just "put out there"? Google for other articles on the same topic.

AHS
-- 
Last week I helped my friend stay put. It's a lot easier'n helpin' 'em
move. I just went over to his house and made sure that he did not start
to load shit into a truck.
-- Mitch Hedberg

[toc] | [prev] | [next] | [standalone]


#12904

FromNovice <novice@example..com>
Date2012-03-12 17:43 +0000
Message-ID<XnsA0148BB42FDABjpnasty@94.75.214.39>
In reply to#12890
Arved Sandstrom <asandstrom3minus1@eastlink.ca> wrote in
news:yPa7r.13504$wf.12231@newsfe09.iad: 

> On 12-03-11 06:54 PM, Novice wrote:
>> Lew <noone@lewscanon.com> wrote in
>> news:jjipli$np7$1@news.albasani.net: 
>> 
> [ SNIP ]
> 
>>> We've discussed this before, remember?
>>>
>>> It's not expensive. When you're calling a logger statement for an
>>> error, the cost of the error SWAMPS the time in the logger. Think
>>> about it. 
>>>
>> I suppose I'm too easily swayed by other opinions. Arved, who seems
>> very knowledgeable, cited that article, which seemed to give it his
>> seal of approval. I don't know the author of the article but I tend
>> to assume he must be an expert to be asked to write about a Java
>> topic. The author cites people who he considers experts and the
>> upshot is that the advice seems to argue against putting positioning
>> information in the log unless its necessary (which it probably isn't
>> if the stacktrace is in the log). Now you make a persuasive argument
>> contradicting the article. I'm satisfied that you have serious
>> expertise in this area so I have no reason to dismiss your argument.
>> But why didn't the experts who wrote the article modify their remarks
>> accordingly? 
> [ SNIP ]
> 
> The article did have my "seal of approval". That's to say, I read the
> article, and agreed with most of it. Not 100 percent, but most of it.
> And I didn't see anything in it which would lead a person down the
> garden path. I recommend it because it's a useful read...but you
> shouldn't accept it as the gospel, just as you shouldn't accept
> "Effective Java" as the gospel either.
> 
Absolutely. Please understand that I didn't mean to imply that you gave 
your whole-hearted endorsement to every bit of it. I just meant that 
you'd suggested it in an approving manner, which suggested that it was 
basically sound, not necessarily perfect in every detail.

> Logging is also a somewhat subjective matter. That's why different
> opinions on different specifics. Ultimately TIMTOWTDI, to borrow a
> Perl motto.
I dabbled in Perl briefly some years ago but didn't know that acronym. 
But, as Lew likes to remind me, Google is my friend so now I know what it 
means ;-)

> What really counts is when the rubber meets the road, and
> the logs have to be _used_, did the ops support people get what they
> needed out of the logs, without too much anguish?
>
That makes perfect sense to me.
 
> You've heard different viewpoints - mine and others' - on including
> positional informational in logs. In the final analysis what matters
> is the sufficiency of information in the logs. Don't worry overmuch
> about logging performance until it's a problem; the whole point of
> having layouts in a properties file is that you can tweak them if
> necessary. I have a specific reason why I don't normally include
> certain positional information, except for error stacktraces, but
> someone else might have a good reason for why they do want this info.
> 
Speaking with my programmer hat on, I tend to find that the stacktrace 
meets most of my needs. I mostly use the class name, method name, and 
line numbers to see where the problem is and what the message is. And I 
don't tend to worry about performance until it starts to become an 
obvious problem either. But I always start feeling a bit anxious when 
people start talking about performance and wonder if I'm shooting myself 
(or my system) in the foot with the techniques I use. But, so far, that 
hasn't been a frequent problem. 

> One note: *never* assume that because somebody has an article in a
> blog or an Internet magazine or a dead tree magazine or even a
> scholarly journal that they are experts. Check the references. Check
> the style of the prose: are the conclusions backed up by
> understandable argument, or are they just "put out there"? Google for
> other articles on the same topic. 
> 
In all honesty, I had that in the back of my mind too. I don't really 
blindly assume that everything I read is written by an expert. I tend to 
give people the benefit of the doubt, especially in topics where I have 
minimal knowledge, but I know that some articles are just nonsense. But 
if a guy who knows his stuff (like you) recommends an article to me and 
it is in a journal that I haven't actually heard trashed by someone 
knowledgable, I tend to assume that knowledgable editors will have done a 
conscientious job of keeping out anything that is complete nonsense. But 
I realize that is hardly a bulletproof approach. So I do retain some 
basic skepticism about things I read ;-)

-- 
Novice

[toc] | [prev] | [next] | [standalone]


#12867

FromPatricia Shanahan <pats@acm.org>
Date2012-03-11 11:14 -0700
Message-ID<zKidnZT6-s8LdsHSnZ2dnUVZ_sWdnZ2d@earthlink.com>
In reply to#12862
On 3/11/2012 10:05 AM, Novice wrote:
> Lew<noone@lewscanon.com>  wrote in news:jjh39f$crc$1@news.albasani.net:
>
>> Novice wrote:
>> snip
>>> I have a utility class called LocalizationUtils which basically
>>> houses convenience methods dealing with i18n/l10n. One of its methods
>>> is getResources(). It expects two parameters, a String representing
>>> the "base name" (the leading part of the resource file name) and a
>>> locale.
>>>
>>> Here's the code for getResources() with all comments and error
>>> handling (aside from the empty catch block) stripped out:
>>>
>>> ====================================================================
>>> static public ResourceBundle getResources(String baseName, Locale
>>> locale {
>>>     ResourceBundle locList = null;
>>
>> Don't use throwaway initializations, usually.
>>
> Why?
>
> If I omit that line and simply use the following in the try block:
>
> ResourceBundle locList = ResourceBundle.getBundle(baseName, locale);
>
> locList isn't visible after the try/catch so that I can return it.

There are two issues, where to declare the variable and whether to
initialize it. The visibility issue means you have to declare it outside
the try/catch.

The issue is whether to initialize it in the declaration. If you do
that, you throw away some compile time checking. Does every path leading
to the return assign an appropriate value to locList?

There are a few situations in which a human programmer can tell that all
necessary assignments are being done, but the compiler cannot. In those
cases you may need to initialize in the declaration, but that is not the
way to start.

Even if I wanted to return null if you go through the catch block, I
would explicitly assign null in the catch block. Doing so shows future
readers, myself included, that I thought about the issue and meant it to
be null if the exception happened.


>
>
>
>>>     try {
>>>       locList = ResourceBundle.getBundle(baseName, locale);
>>>         }
>>>     catch (MissingResourceException mrExcp) {
>>
>> Log and return 'null' if that's the recovery strategy for this
>> exception.
>>
> Is that what I should do, return null if there is a problem getting the
> resource?

How do you intend this method to be used? What does its Javdoc comment
say about missing resource bundles?

I generally prefer throwing exceptions to returning null in this sort of
situation. The reasoning is that the caller may want to take different
actions for different failures. Returning null, even after logging the
details, deprives the caller of any way of distinguishing different
cases. I realize this particular method currently only has one error
case, but that may change later.

>
> I'm not sure if I should be returning anything at all. Maybe I should
> just log and stop the program?

Direct exit from a low level method is rarely a good idea. It limits its
usefulness. Generally, you should pass the buck up the stack, for
example by throwing an exception or returning null.

If you do that, your method can be used in contexts in which the missing
resource bundle is not fatal. Maybe the call arguments were derived from
GUI input. In that case, the user should be told about the problem and
invited to change the input. Maybe one transaction depends on the
resource bundle, and that transaction needs to be aborted, but the
program can keep on going.

Even in a batch program, you may be part way through processing some
input, and it is possible to do more validation, and find more input
errors, in a single run.

Or maybe there is a sensible default, and your caller knows what it is.
If you throw an exception or return a result that specifically indicates
missing resource bundle, the caller can use the default.

If you throw an exception, and this really is a situation in which the
correct action is to terminate the program, the exception will filter up
the stack to a level that knows, for example, that it is the main method
in a batch program. It can call System.exit with the appropriate error code.

Patricia

[toc] | [prev] | [next] | [standalone]


#12884

FromNovice <novice@example..com>
Date2012-03-11 22:35 +0000
Message-ID<XnsA013BD1676773jpnasty@94.75.214.39>
In reply to#12867
Patricia Shanahan <pats@acm.org> wrote in
news:zKidnZT6-s8LdsHSnZ2dnUVZ_sWdnZ2d@earthlink.com: 

> On 3/11/2012 10:05 AM, Novice wrote:
>> Lew<noone@lewscanon.com>  wrote in
>> news:jjh39f$crc$1@news.albasani.net: 
>>
>>> Novice wrote:
>>> snip
>>>> I have a utility class called LocalizationUtils which basically
>>>> houses convenience methods dealing with i18n/l10n. One of its
>>>> methods is getResources(). It expects two parameters, a String
>>>> representing the "base name" (the leading part of the resource file
>>>> name) and a locale.
>>>>
>>>> Here's the code for getResources() with all comments and error
>>>> handling (aside from the empty catch block) stripped out:
>>>>
>>>> ====================================================================
>>>> static public ResourceBundle getResources(String baseName, Locale
>>>> locale {
>>>>     ResourceBundle locList = null;
>>>
>>> Don't use throwaway initializations, usually.
>>>
>> Why?
>>
>> If I omit that line and simply use the following in the try block:
>>
>> ResourceBundle locList = ResourceBundle.getBundle(baseName, locale);
>>
>> locList isn't visible after the try/catch so that I can return it.
> 
> There are two issues, where to declare the variable and whether to
> initialize it. The visibility issue means you have to declare it
> outside the try/catch.
> 
> The issue is whether to initialize it in the declaration. If you do
> that, you throw away some compile time checking. Does every path
> leading to the return assign an appropriate value to locList?
> 
> There are a few situations in which a human programmer can tell that
> all necessary assignments are being done, but the compiler cannot. In
> those cases you may need to initialize in the declaration, but that is
> not the way to start.
> 
> Even if I wanted to return null if you go through the catch block, I
> would explicitly assign null in the catch block. Doing so shows future
> readers, myself included, that I thought about the issue and meant it
> to be null if the exception happened.
> 
That's where I went wrong. As I recall, I got into the habit of 
initializing every variable (with the odd exception) when I declare it 
simply to avoid compiler warnings about the value potentially being null  
later in the code. I didn't think it through very thoroughly and just 
started slavishly initializing everything upon being declared. It 
certainly worked for getting rid of compiler warnings but it wasn't 
nearly as smart as figuring out when it needed to happen and when it was 
ill-advised.

I'll need to start working on that....
> 
>>
>>
>>
>>>>     try {
>>>>       locList = ResourceBundle.getBundle(baseName, locale);
>>>>         }
>>>>     catch (MissingResourceException mrExcp) {
>>>
>>> Log and return 'null' if that's the recovery strategy for this
>>> exception.
>>>
>> Is that what I should do, return null if there is a problem getting
>> the resource?
> 
> How do you intend this method to be used? What does its Javdoc comment
> say about missing resource bundles?
> 
In short, if the baseName is null or misspelled, I can't think of a 
plausible recovery strategy so I'm (now) inclined to show the user a 
message that the program can't continue in a simple dialog with an Okay 
button; when he presses that, the program gets closed.

I'm still struggling a bit with the missing locale. I _could_ determine 
the default locale via Locale.getDefault() and it _might_ be different 
than the one determined in the program, Foo, in which case I _could_ go 
ahead and try to find the bundle for the default locale. But if it's a 
different language than the one the user wanted, I'm not sure I'm doing 
him a favor to show him a language he may not know. So I may treat the 
null locale scenario as being just an unrecoverable as the missing or 
incorrect baseName.

> I generally prefer throwing exceptions to returning null in this sort
> of situation. The reasoning is that the caller may want to take
> different actions for different failures. Returning null, even after
> logging the details, deprives the caller of any way of distinguishing
> different cases. I realize this particular method currently only has
> one error case, but that may change later.
>
Well, it's actually got three error cases: a null baseName, a null 
locale, and a baseName that doesn't have a corresponding file, which is 
caused by a spelling mistake in the base name. But I would certainly log 
a distinct message in any of those cases. 
>>
>> I'm not sure if I should be returning anything at all. Maybe I should
>> just log and stop the program?
> 
> Direct exit from a low level method is rarely a good idea. It limits
> its usefulness. Generally, you should pass the buck up the stack, for
> example by throwing an exception or returning null.
> 
> If you do that, your method can be used in contexts in which the
> missing resource bundle is not fatal. Maybe the call arguments were
> derived from GUI input. In that case, the user should be told about
> the problem and invited to change the input. Maybe one transaction
> depends on the resource bundle, and that transaction needs to be
> aborted, but the program can keep on going.
> 
> Even in a batch program, you may be part way through processing some
> input, and it is possible to do more validation, and find more input
> errors, in a single run.
> 
> Or maybe there is a sensible default, and your caller knows what it
> is. If you throw an exception or return a result that specifically
> indicates missing resource bundle, the caller can use the default.
> 
I see what you're saying. In my particular situation, the missing 
resource bundle is a show-stopper but in other cases it might not be so 
it makes more sense to let getLocalizedText deal with that than to handle 
it in getResources(). And in some cases it might make sense to push it up 
even higher, even right up to main(). 

Okay, on the theory that some other program MAY be able to carry on even 
if the resources are missing - even though I can't think of a convincing 
case right this minute - I'll let getResources() log the problem and 
throw an exception, then let getLocalizedText() handle it. In my case, 
it's going to show a simple "Program ending" dialog with an okay button 
and pushing it is going to stop the program. That way, some future 
program that can carry on without the resources will be free to respond 
in some different way.

> If you throw an exception, and this really is a situation in which the
> correct action is to terminate the program, the exception will filter
> up the stack to a level that knows, for example, that it is the main
> method in a batch program. It can call System.exit with the
> appropriate error code. 
> 
And that brings up a minor point that I've wondered about for a while. Is 
there any standard approach to the integers that are used in System.exit
(). For instance, does a value of 16 typically indicate a severe error 
while a 4 indicates a minor error? (I'm thinking of the old IBM mainframe 
codes in my example.) It seems to me that the Java community may have 
some conventions in this regard that I should follow....


-- 
Novice

[toc] | [prev] | [next] | [standalone]


#12892

FromLew <noone@lewscanon.com>
Date2012-03-11 16:58 -0700
Message-ID<jjje72$984$2@news.albasani.net>
In reply to#12884
Novice wrote:
> And that brings up a minor point that I've wondered about for a while. Is
> there any standard approach to the integers that are used in System.exit
> (). For instance, does a value of 16 typically indicate a severe error
> while a 4 indicates a minor error? (I'm thinking of the old IBM mainframe
> codes in my example.) It seems to me that the Java community may have
> some conventions in this regard that I should follow....

No.

It parallels the use in C of exit values. What's the standard in C?

You can answer your own question yourself from first principles. You should 
get in the habit of doing that. What is the purpose of the return value of the 
program? What uses that value? How does it use that value?

-- 
Lew
Honi soit qui mal y pense.
http://upload.wikimedia.org/wikipedia/commons/c/cf/Friz.jpg

[toc] | [prev] | [next] | [standalone]


#12900

FromNovice <novice@example..com>
Date2012-03-12 15:44 +0000
Message-ID<XnsA014778644316jpnasty@94.75.214.39>
In reply to#12892
Lew <noone@lewscanon.com> wrote in news:jjje72$984$2@news.albasani.net:

> Novice wrote:
>> And that brings up a minor point that I've wondered about for a
>> while. Is there any standard approach to the integers that are used
>> in System.exit (). For instance, does a value of 16 typically
>> indicate a severe error while a 4 indicates a minor error? (I'm
>> thinking of the old IBM mainframe codes in my example.) It seems to
>> me that the Java community may have some conventions in this regard
>> that I should follow.... 
> 
> No.
> 
> It parallels the use in C of exit values. What's the standard in C?
> 
Not being a C programmer, I don't know. But I googled and all Wikipedia 
says is that 0 means success and 1 means failure. Another article was 
more elaborate but, this sentence expresses the essence: "Your program 
should follow an existing convention if an existing convention makes 
sense for it". In other words, there is no widely-used standard 
convention for the value of the integer in exit().

And that's fine. As usual, it means follow the shop standard if there is 
one; otherwise you can do what you like.

> You can answer your own question yourself from first principles. You
> should get in the habit of doing that. What is the purpose of the
> return value of the program? What uses that value? How does it use
> that value? 
> 

That's closer to the thought process I'd use if I was trying to _create_ 
a convention. I was trying to determine if there is already a convention 
out there that the majority of skilled professionals are using so that I 
could use it. 

After further googling, I'm not seeing any. In that case, I'll follow a 
shop standard if there is one and do my own thing if there isn't, keeping 
to the "0 is fine and everything else is bad news" convention.

-- 
Novice

[toc] | [prev] | [next] | [standalone]


#12903

FromGene Wirchenko <genew@ocis.net>
Date2012-03-12 10:34 -0700
Message-ID<rpcsl7p4vftek7nkh9l217ccqodhjqn1mj@4ax.com>
In reply to#12900
On Mon, 12 Mar 2012 15:44:49 +0000 (UTC), Novice <novice@example..com>
wrote:

[snip]

>Not being a C programmer, I don't know. But I googled and all Wikipedia 
>says is that 0 means success and 1 means failure. Another article was 
>more elaborate but, this sentence expresses the essence: "Your program 
>should follow an existing convention if an existing convention makes 
>sense for it". In other words, there is no widely-used standard 
>convention for the value of the integer in exit().

     Well, there is.  0 and 1 is the standard.  The more elaborate
article has it wrong.  Now, quite commonly, the return value is used
by the operating system as a return code, but this is not part of the
C standard.

[snip]

Sincerely,

Gene Wirchenko

[toc] | [prev] | [next] | [standalone]


#12869

FromArivald <NOSPAMarivald@interia.pl>
Date2012-03-11 20:34 +0100
Message-ID<jjiusj$g53$1@news.dialog.net.pl>
In reply to#12862
W dniu 2012-03-11 18:05, Novice pisze:
> Lew<noone@lewscanon.com>  wrote innews:jjh39f$crc$1@news.albasani.net:
>
>> >  Novice wrote:
>> >  snip
>>> >>  I have a utility class called LocalizationUtils which basically
>>> >>  houses convenience methods dealing with i18n/l10n. One of its methods
>>> >>  is getResources(). It expects two parameters, a String representing
>>> >>  the "base name" (the leading part of the resource file name) and a
>>> >>  locale.
>>> >>
>>> >>  Here's the code for getResources() with all comments and error
>>> >>  handling (aside from the empty catch block) stripped out:
>>> >>
>>> >>  ====================================================================
>>> >>  static public ResourceBundle getResources(String baseName, Locale
>>> >>  locale {
>>> >>      ResourceBundle locList = null;
>> >
>> >  Don't use throwaway initializations, usually.
>> >
> Why?
>
> If I omit that line and simply use the following in the try block:
>
> ResourceBundle locList = ResourceBundle.getBundle(baseName, locale);
>
> locList isn't visible after the try/catch so that I can return it.
>

Simplest solution, skip variable at all.

static public ResourceBundle getResources(
	String baseName, Locale locale) {
   try {
     return ResourceBundle.getBundle(baseName, locale);
   } catch (MissingResourceException e) {
     logger.error('missing resource', e);
     return null;
   }
}


or, if you need to do something on variable:

   try {
     ResourceBundle locList = ResourceBundle.getBundle(baseName, locale);

     ... do something ...

     return locList;

   } catch (MissingResourceException e) {
     logger.error('missing resource', e);
     return null;
   }


or if you want exception block only for ResourceBundle.getBundle()

   ResourceBundle locList; // no null assignment, simply uninitialized
   try {
     locList = ResourceBundle.getBundle(baseName, locale);
   } catch (MissingResourceException e) {
     logger.error('missing resource', e);
     return null;
   }

   do something with locList ...

   return locList;



-- 
Arivald

[toc] | [prev] | [next] | [standalone]


#12886

FromNovice <novice@example..com>
Date2012-03-11 22:36 +0000
Message-ID<XnsA013BD41A8847jpnasty@94.75.214.39>
In reply to#12869
Arivald <NOSPAMarivald@interia.pl> wrote in
news:jjiusj$g53$1@news.dialog.net.pl: 

> W dniu 2012-03-11 18:05, Novice pisze:
>> Lew<noone@lewscanon.com>  wrote
>> innews:jjh39f$crc$1@news.albasani.net: 
>>
>>> >  Novice wrote:
>>> >  snip
>>>> >>  I have a utility class called LocalizationUtils which basically
>>>> >>  houses convenience methods dealing with i18n/l10n. One of its
>>>> >>  methods is getResources(). It expects two parameters, a String
>>>> >>  representing the "base name" (the leading part of the resource
>>>> >>  file name) and a locale.
>>>> >>
>>>> >>  Here's the code for getResources() with all comments and error
>>>> >>  handling (aside from the empty catch block) stripped out:
>>>> >>
>>>> >>  ================================================================
>>>> >>  ==== static public ResourceBundle getResources(String baseName,
>>>> >>  Locale locale {
>>>> >>      ResourceBundle locList = null;
>>> >
>>> >  Don't use throwaway initializations, usually.
>>> >
>> Why?
>>
>> If I omit that line and simply use the following in the try block:
>>
>> ResourceBundle locList = ResourceBundle.getBundle(baseName, locale);
>>
>> locList isn't visible after the try/catch so that I can return it.
>>
> 
> Simplest solution, skip variable at all.
> 
> static public ResourceBundle getResources(
>      String baseName, Locale locale) {
>    try {
>      return ResourceBundle.getBundle(baseName, locale);
>    } catch (MissingResourceException e) {
>      logger.error('missing resource', e);
>      return null;
>    }
> }
> 
> 
> or, if you need to do something on variable:
> 
>    try {
>      ResourceBundle locList = ResourceBundle.getBundle(baseName,
>      locale); 
> 
>      ... do something ...
> 
>      return locList;
> 
>    } catch (MissingResourceException e) {
>      logger.error('missing resource', e);
>      return null;
>    }
> 
> 
> or if you want exception block only for ResourceBundle.getBundle()
> 
>    ResourceBundle locList; // no null assignment, simply uninitialized
>    try {
>      locList = ResourceBundle.getBundle(baseName, locale);
>    } catch (MissingResourceException e) {
>      logger.error('missing resource', e);
>      return null;
>    }
> 
>    do something with locList ...
> 
>    return locList;
> 
> 
> 

Thanks, Arivald. I like your suggestions.



-- 
Novice

[toc] | [prev] | [next] | [standalone]


#12907

FromArne Vajhøj <arne@vajhoej.dk>
Date2012-03-12 14:41 -0400
Message-ID<4f5e4341$0$293$14726298@news.sunsite.dk>
In reply to#12859
On 3/10/2012 9:39 PM, Lew wrote:
> Novice wrote:
[lot if stuff that I agree with cut out]
>> One other questions. When, if ever, should I execute System.exit() with a
>> non-zero integer? In my example, I know that program Foo can't proceed
>
> Never. Program exit should be under user control.

I don't s much point in "This app is completely fubar. Do you want to
exit or do you want to experience random behavior including possible
data corruption?".

:-)

Arne

[toc] | [prev] | [next] | [standalone]


#12906

FromArne Vajhøj <arne@vajhoej.dk>
Date2012-03-12 14:37 -0400
Message-ID<4f5e4260$0$293$14726298@news.sunsite.dk>
In reply to#12858
On 3/10/2012 8:51 PM, Novice wrote:
> I've been trying to get my head around exception handling for the last
> few days concurrently with my efforts to start doing logging correctly.
>
> I've re-read the Java Tutorials section on exception handling. I read
> Bloch's remarks on Exception Handling in Effective Java (2nd edition)
> several days ago. I'm working my way through Stelting's Robust Java.
>
> It's time to ask some questions to make sure I'm on the right track.
>
> I'm struggling with the best way to revise some of my existing code.
> Let's consider a concrete example and then see if we can generalize to
> come up with a proper error handling strategy.
>
> I have a utility class called LocalizationUtils which basically houses
> convenience methods dealing with i18n/l10n. One of its methods is
> getResources(). It expects two parameters, a String representing the
> "base name" (the leading part of the resource file name) and a locale.

> In terms of trouble spots, I know from experience that getResources()
> will throw a MissingResourceException, which is an unchecked exception,
> if the base name is misspelled. A null value in either parameter is also
> going to make the getResources() method fail: ResourceBundle.getBundle()
> will throw a NullPointerException if either parameter is null.
>
> My objective is to code getResources() and getLocalizedText() as
> professionally as possible. If the methods fail, I want to write a clear
> message to my log and the log record needs to include a stacktrace. (I'm
> assuming that a console is not necessarily available to the operators
> running this program and I need to know where the error took place. Based
> on an article Arved suggested in another thread,
> http://www.javacodegeeks.com/2011/01/10-tips-proper-application-
> logging.html, I'm inclined to minimize "position" information - class
> name, method name, line number - in the log and instead get all of that
> from the stacktrace.)

I would not worry about the performance until you know that you
have a problem.

> Since the only exceptions I anticipate, MissingResourceException and
> NullPointerException, are unchecked exceptions, I gather than I shouldn't
> really do anything about them aside from logging when they happen.

If you only log - then what?

>                                                                    Okay,
> fair enough; I certainly don't want to display the source code to my
> user, make them enter the correct value for the baseName, make them
> recompile the program and then run it again! But when/where should I log
> the error? For instance, if I mess up my coding somehow and inadvertently
> pass a null in the baseName, should getResources() be testing its input
> parameters individually to see if they are null and write a message to
> the log if they are null from within that method? I'm inclined to say yes
> to that but I'm not sure what to do next. It seems pointless to carry on
> with getResources() since ResourceBundle.getBundle(baseName, locale)
> will fail on a NullPointerException with a null in either parameter. I
> could throw a NullPointerException so that getLocalizedText() can deal
> with it. But how do I get a stacktrace into the log if I follow that
> strategy? It's easy enough to get the stacktrace once I've caught an
> exception but I'm just talking about recognizing that an input parameter
> is null; there's no exception at that point to put in my log.
>
> If I let getResources() throw NullPointerException if either parameter is
> null, then I can let getLocalizedText() catch those NullPointerExceptions
> and get the stacktraces from the exception and write them to the log. In
> that case, I may as well just check the input parameters for nulls, and
> simply throw NullPointerException with a specific message within
> getResources(); then getLocalizedText() can have a try/catch block. The
> try/catch can detect the NullPointerException and write both the message
> and the stacktrace to the log.
>
> But I gather that you should handle the error as close to where it
> happened as possible when you can. I'd tend to prefer to handle the null
> parameter values in getResources() except that I'm not sure how to write
> the stack trace to the log before any exception has happened.

Do you need the stacktrace in that case?

> One other questions. When, if ever, should I execute System.exit() with a
> non-zero integer?

When you want to terminate the program with an error status to the
shell.

Arne

[toc] | [prev] | [next] | [standalone]


#12926

FromNovice <novice@example..com>
Date2012-03-12 22:43 +0000
Message-ID<XnsA014BE740A491jpnasty@94.75.214.39>
In reply to#12906
Arne Vajhøj <arne@vajhoej.dk> wrote in
news:4f5e4260$0$293$14726298@news.sunsite.dk: 

> On 3/10/2012 8:51 PM, Novice wrote:
>> I've been trying to get my head around exception handling for the
>> last few days concurrently with my efforts to start doing logging
>> correctly. 
>>
>> I've re-read the Java Tutorials section on exception handling. I read
>> Bloch's remarks on Exception Handling in Effective Java (2nd edition)
>> several days ago. I'm working my way through Stelting's Robust Java.
>>
>> It's time to ask some questions to make sure I'm on the right track.
>>
>> I'm struggling with the best way to revise some of my existing code.
>> Let's consider a concrete example and then see if we can generalize
>> to come up with a proper error handling strategy.
>>
>> I have a utility class called LocalizationUtils which basically
>> houses convenience methods dealing with i18n/l10n. One of its methods
>> is getResources(). It expects two parameters, a String representing
>> the "base name" (the leading part of the resource file name) and a
>> locale. 
> 
>> In terms of trouble spots, I know from experience that getResources()
>> will throw a MissingResourceException, which is an unchecked
>> exception, if the base name is misspelled. A null value in either
>> parameter is also going to make the getResources() method fail:
>> ResourceBundle.getBundle() will throw a NullPointerException if
>> either parameter is null. 
>>
>> My objective is to code getResources() and getLocalizedText() as
>> professionally as possible. If the methods fail, I want to write a
>> clear message to my log and the log record needs to include a
>> stacktrace. (I'm assuming that a console is not necessarily available
>> to the operators running this program and I need to know where the
>> error took place. Based on an article Arved suggested in another
>> thread, 
>> http://www.javacodegeeks.com/2011/01/10-tips-proper-application- 
>> logging.html, I'm inclined to minimize "position" information - class 
>> name, method name, line number - in the log and instead get all of
>> that from the stacktrace.)
> 
> I would not worry about the performance until you know that you
> have a problem.
> 
>> Since the only exceptions I anticipate, MissingResourceException and
>> NullPointerException, are unchecked exceptions, I gather than I
>> shouldn't really do anything about them aside from logging when they
>> happen. 
> 
> If you only log - then what?
> 
>>                                                                   
>>                              Okay, 
>> fair enough; I certainly don't want to display the source code to my
>> user, make them enter the correct value for the baseName, make them
>> recompile the program and then run it again! But when/where should I
>> log the error? For instance, if I mess up my coding somehow and
>> inadvertently pass a null in the baseName, should getResources() be
>> testing its input parameters individually to see if they are null and
>> write a message to the log if they are null from within that method?
>> I'm inclined to say yes to that but I'm not sure what to do next. It
>> seems pointless to carry on with getResources() since
>> ResourceBundle.getBundle(baseName, locale) will fail on a
>> NullPointerException with a null in either parameter. I could throw a
>> NullPointerException so that getLocalizedText() can deal with it. But
>> how do I get a stacktrace into the log if I follow that strategy?
>> It's easy enough to get the stacktrace once I've caught an exception
>> but I'm just talking about recognizing that an input parameter is
>> null; there's no exception at that point to put in my log. 
>>
>> If I let getResources() throw NullPointerException if either
>> parameter is null, then I can let getLocalizedText() catch those
>> NullPointerExceptions and get the stacktraces from the exception and
>> write them to the log. In that case, I may as well just check the
>> input parameters for nulls, and simply throw NullPointerException
>> with a specific message within getResources(); then
>> getLocalizedText() can have a try/catch block. The try/catch can
>> detect the NullPointerException and write both the message and the
>> stacktrace to the log. 
>>
>> But I gather that you should handle the error as close to where it
>> happened as possible when you can. I'd tend to prefer to handle the
>> null parameter values in getResources() except that I'm not sure how
>> to write the stack trace to the log before any exception has
>> happened. 
> 
> Do you need the stacktrace in that case?
> 

Yes. I call getResources() from several places in the program and just 
knowing getResources() was called doesn't tell me which call had the 
problem. Was it the call in the main menu that launches the program? Was 
it the call in the program itself that sets up the GUI? Was it the call 
in the preferences dialog? etc. So I'm going to have trouble determining 
which bundle was desired unless I know at least the method which called 
getResources(). Now, if getResources() was only invoked once in the life 
of the program, just knowing that it happened would be all I'd need to 
know what it was trying to find. 

>> One other questions. When, if ever, should I execute System.exit()
>> with a non-zero integer?
> 
> When you want to terminate the program with an error status to the
> shell.
>
Okay, thanks.
> 
-- 
Novice

[toc] | [prev] | [next] | [standalone]


#12927

FromLew <lewbloch@gmail.com>
Date2012-03-12 16:11 -0700
Message-ID<5985652.620.1331593875104.JavaMail.geo-discussion-forums@pbboc6>
In reply to#12926
Novice wrote:
> Arne Vajhøj wrote:
>> Do you need the stacktrace in that case?
> 
> Yes. I call getResources() from several places in the program and just 
> knowing getResources() was called doesn't tell me which call had the 
> problem. Was it the call in the main menu that launches the program? Was 
> it the call in the program itself that sets up the GUI? Was it the call 
> in the preferences dialog? etc. So I'm going to have trouble determining 
> which bundle was desired unless I know at least the method which called 
> getResources(). Now, if getResources() was only invoked once in the life 
> of the program, just knowing that it happened would be all I'd need to 
> know what it was trying to find. 

None of that explains why you need a stack trace instead of other ways to get those data. Why do you prefer the stack trace to other techniques?

Mind you, I'm not arguing against a stack trace. Have you looked at your log output to see if the stack trace is usable information?

Well, have you?

>>> One other questions. When, if ever, should I execute System.exit()
>>> with a non-zero integer?
>> 
>> When you want to terminate the program with an error status to the
>> shell.
>>
> Okay, thanks.

This is the same answer, in its essentials, that you keep getting over and over.

Over and over we tell you, "What is the use that will get?"

So, what is the use that will get?

This has two parts: What will use the exit code? What will it do with the exit code?

Well, what will?

-- 
Lew

[toc] | [prev] | [next] | [standalone]


#12937

FromArivald <NOSPAMarivald@interia.pl>
Date2012-03-13 00:54 +0100
Message-ID<jjm2fu$191$1@news.dialog.net.pl>
In reply to#12926
W dniu 2012-03-12 23:43, Novice pisze:
> Arne Vajhřj<arne@vajhoej.dk>  wrote in
>
>> Do you need the stacktrace in that case?
>>
>
> Yes. I call getResources() from several places in the program and just
> knowing getResources() was called doesn't tell me which call had the
> problem. Was it the call in the main menu that launches the program? Was
> it the call in the program itself that sets up the GUI? Was it the call
> in the preferences dialog? etc. So I'm going to have trouble determining

Instead of stack trace, you may be more interested in resource ID 
program try to load and failed. If You fix missing resource, it will 
work in all places.

Just add resource name and locale data to log message.

-- 
Arivald

[toc] | [prev] | [next] | [standalone]


#12947

FromArved Sandstrom <asandstrom3minus1@eastlink.ca>
Date2012-03-13 06:05 -0300
Message-ID<X5E7r.36034$L12.15480@newsfe23.iad>
In reply to#12937
On 12-03-12 08:54 PM, Arivald wrote:
> W dniu 2012-03-12 23:43, Novice pisze:
>> Arne Vajhřj<arne@vajhoej.dk>  wrote in
>>
>>> Do you need the stacktrace in that case?
>>>
>>
>> Yes. I call getResources() from several places in the program and just
>> knowing getResources() was called doesn't tell me which call had the
>> problem. Was it the call in the main menu that launches the program? Was
>> it the call in the program itself that sets up the GUI? Was it the call
>> in the preferences dialog? etc. So I'm going to have trouble determining
> 
> Instead of stack trace, you may be more interested in resource ID
> program try to load and failed. If You fix missing resource, it will
> work in all places.
> 
> Just add resource name and locale data to log message.
> 
Agreed. In the general case, simply make sure that your log statements
print enough stuff. It's much less useful, than you might think, to know
who the caller was; the main reason people believe it's important is
because they forgot to log enough data and so are desperate to somehow
recover that by guessing from the calling context.

Static analysis as part of debugging will tell you the potential
callers. If it's really important to know what did call, hey, just log
the potential calling sites also: you have a log statement in
getResources() and a statement in each of the N methods that use
getResources().

Keep stack traces for errors. Rely on a flow of single-line log entries
to help you trace a flow of execution. It's uniform, easier to analyze
with a variety of tools. Logging is cheap this way. No harm done if you
add log statements; you can switch them on and off by class or package
as needed at various levels. If you log like this the only stack traces
that you see belong to real errors.

Make your life easier by enhancing your messages. slf4j helps out with
this by providing argument placeholders, but it's easy to do this
yourself with java.text.MessageFormat. Keep your log message format
strings in a properties file, and consider a utility class that loads
these, and can be accessed at logging time with a property key and the
log message arguments. This utility class uses MessageFormat to do the
work, and returns a fully formatted message to the site of the log.

Consider all the extra identifiers in a message that help trace a flow
of execution: thread ID, logged-in user in a web application etc. Use
PatternLayout (log4j) or similar, or other helper methods
(getAuthenticatedUser() in your utility class) to simplify this framing.

HTH,
AHS

-- 
Last week I helped my friend stay put. It's a lot easier'n helpin' 'em
move. I just went over to his house and made sure that he did not start
to load shit into a truck.
-- Mitch Hedberg

[toc] | [prev] | [standalone]


Page 2 of 2 — ← Prev page 1 [2]

Back to top | Article view | comp.lang.java.programmer


csiph-web