aspose file tools*
The moose likes Beginning Java and the fly likes Exception handling and Recovery Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Exception handling and Recovery" Watch "Exception handling and Recovery" New topic
Author

Exception handling and Recovery

Jack Moore Iii
Ranch Hand

Joined: Jun 07, 2012
Posts: 76
Ok, so this is one part of Java or C++ I never got. Because I always wrote code that I knew how to use.

So you take in a string that suppose to be an int, but it's not, and it throws an exception:



So it prints out the error message, and still continues the program. How do you get the program to understand an error was made? Does the exception value variable still exist to check to see if it has a value and therefore exit the program gracefully, or prompt the user again to enter valid input? I don't know if this is considered a basic and obvious code thing that I should know inside and out, but I've never been able to grasp it, simply because I don't care about the people using my code other than me. But yeah, you get paid to care eventually, so that takes care of that, hah...
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61232
    
  66

What do you want the code to do when there's a bad number entered?

Simply printing out "wrong" is pretty foolish, no? What should it do?


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Jack Moore Iii
Ranch Hand

Joined: Jun 07, 2012
Posts: 76
I thought I pointed out that it would either exit gracefully with out a bunch of run time error crap text or would re-prompt the user to enter something valid. When an error is caught, how do you recover? They don't want you using system.exit() either. It seems confusing to me, but probably because I've never done it before...
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3015
    
  10
Jack Moore Iii wrote:So it prints out the error message, and still continues the program.

That depends on where you put the rest of the program. In the example given, there isn't any other code shown, so it doesn't do anything after the error. But consider your options - if you want the program to doSomethingElse(), where should you put that instruction?

Or

Which makes more sense?

You can also consider simply not catching the exception. Or catching it and throwing another exception, or catching it and calling System.exit(1).
Jack Moore Iii
Ranch Hand

Joined: Jun 07, 2012
Posts: 76


I'm doing the 3rd code assignment on the Cattle Drive page. I want it to do something else, but that something else requires that I have a valid string that turns into an integer. If I don't have that, I need to just exit properly. Or if this didn't rely on command line arguments, and instead it was a readline prompt, I'd need that error to be caught alone without going down through and trying to act upon the "i" variable that isn't correct. If the Integer.parseInt(args[0]) is before the other code in a try block, does the error catch kill all the other code in the try block below the point at which the exception is thrown?...
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3015
    
  10
Jack Moore Iii wrote:If the Integer.parseInt(args[0]) is before the other code in a try block, does the error catch kill all the other code in the try block below the point at which the exception is thrown?...

If I've understood the question correctly, the answer is yes - that's the point of a try-catch block. On an error (or exception really) you skip the rest of the the try block, and jump to the appropriate catch.
Jack Moore Iii
Ranch Hand

Joined: Jun 07, 2012
Posts: 76
So, it is valid and good code to use system.exit(1), or is that discouraged? Also, if I wanted to re-prompt the user to enter valid data, could I just put the entire try/catch block in a while statement with a condition that I set to true every time the catch block is executed? I know there's a lot of stuff I "can" do, but then there's a standard set of things people on the job want you to do that keeps changing every friggn second people with opinions get the chance to enforce those opinions into policy. "Good" code to me is something that compiles and works, so I have to make extra sure I don't fall into the depreciated and such area of Java...
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3015
    
  10
Realistically, you're always going to encounter some variations in people's opinions on these matters, and you have to take everything with a grain of salt unless it's from your employer, or your grader, or a substantial consensus of you co-workers or other peers. And I do not in any way pretend to represent the Cattle Drive folk, so if that's your target, give their opinions much more weight.

That said...

Jack Moore Iii wrote:So, it is valid and good code to use system.exit(1), or is that discouraged?


I think System.exit() is generally frowned on for a variety of reasons. It makes it harder to test or re-use code in other contexts. I would argue that just about the only place it may be appropriate is in a public static void main() method - it gives you control over the exit code, if you're writing a command-line application where anyone cares about the exit code. (That's pretty rare nowadays.) Otherwise, I'd skip it..

Jack Moore Iii wrote:Also, if I wanted to re-prompt the user to enter valid data, could I just put the entire try/catch block in a while statement with a condition that I set to true every time the catch block is executed?

That sounds like a good approach, yes. Or something similar. Within the constraints of Cattle Drive, that's probably what I'd do.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38902
    
  23
I would avoid System.exit myself. It can be a bit vicious, terminating code you want to allow to run to completion. If you are in a non‑threaded application, that is probably not a problem, however.
The problem with Exceptions like that is that you are not working out what to do with the Exception. You are simply catching it, and not going on to think how to try again to get the number. In your later post, you are getting ideas about trying again.

I shall not say any more for the time being.
Jack Moore Iii
Ranch Hand

Joined: Jun 07, 2012
Posts: 76
I have to do something with the exception variable "e" that I caught? I thought that was just syntax to label which catch code block to execute...
Steve Myers
Ranch Hand

Joined: Dec 08, 2012
Posts: 47
One thing you could do is put the try block in a loop that will only terminate if the user enters valid input. Or the user gets 5 trys or whatever and then it exits. I will leave the implementation to you.
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3015
    
  10
Jack Moore Iii wrote:I have to do something with the exception variable "e" that I caught? I thought that was just syntax to label which catch code block to execute...

You don't have to do anything with e, but you can. It's more than just syntax - it gives you a reference to an Exception object (e) that has various methods that may prove useful.

I would argue that any time you aren't entirely sure why a particular exception might be thrown, or what to do about it, you should at least log it somehow, so you know something happened. Preferably, log it in a way that tells you as much as possible about what happened. If you're using a logging framework (like log4j), typically there's a method like logger.error("some message", e) - where e is the exception object. Pass e in as a parameter, and the logger will know how to extract the useful information from the exception. If you're not using a logging framework, then simply calling e.printStackTrace() is a good quick-and-dirty way to achieve the same thing. Only when you're sure you understand the error should you consider not doing this. You don't want to throw away useful debugging info.

Now in this case, it's perfectly plausible we do understand the cause of the error - the user input bad data. So if you construct a loop to keep asking the user for input, until you get good input (preferably explaining what was wrong, if there's a problem) then there's not really much else you need to do. and then you can justifiably not log the error. In which case, maybe there's nothing at all you need to do with "e".
Jack Moore Iii
Ranch Hand

Joined: Jun 07, 2012
Posts: 76
So... e.printStackTrace(); basically makes it so it prints out the same crap, but it doesn't kill the program? I have no idea on the logging aspect, other than appending it to a file, if printStackTrace would even return a string to be able to dump it somewhere like that. I suppose these details might be a bit more advanced than these simple programs call for, but I guess I better learn how to do it now rather than later.

Also, I didn't know the whole Cattle Drive thing was a paid service, so I won't keep posting code, but this:



num = tens[(int)((double)i/10)-1];

num = tens[(int)((double)((i-(i%10))/10))-1] + "-" + ones[i % 10];

The bolded code there with the dual casting. Is that what is considered confusing and bad code to write? Because... it works. And the only other option I see is to split it up into a bunch of variables, because the array needs an int to put in the []'s and you need a double for division. The entire program works just fine now, but I still have no idea what kind of documentation and code employers look for...
Steve Myers
Ranch Hand

Joined: Dec 08, 2012
Posts: 47
Jack Moore Iii wrote:num = tens[(int)((double)i/10)-1];

num = tens[(int)((double)((i-(i%10))/10))-1] + "-" + ones[i % 10];

The bolded code there with the dual casting. Is that what is considered confusing and bad code to write? Because... it works. And the only other option I see is to split it up into a bunch of variables, because the array needs an int to put in the []'s and you need a double for division. The entire program works just fine now, but I still have no idea what kind of documentation and code employers look for...


if (i % 10) == 0) why do you need a double to divide i by 10?
Even if you did need a double (i / 10.0) would work just as well, the compiler inserts the cast.

On the second line I don't see why you need a double either, all I see are ints.
Jack Moore Iii
Ranch Hand

Joined: Jun 07, 2012
Posts: 76
Steve Myers wrote:
Jack Moore Iii wrote:num = tens[(int)((double)i/10)-1];

num = tens[(int)((double)((i-(i%10))/10))-1] + "-" + ones[i % 10];

The bolded code there with the dual casting. Is that what is considered confusing and bad code to write? Because... it works. And the only other option I see is to split it up into a bunch of variables, because the array needs an int to put in the []'s and you need a double for division. The entire program works just fine now, but I still have no idea what kind of documentation and code employers look for...


if (i % 10) == 0) why do you need a double to divide i by 10?
Even if you did need a double (i / 10.0) would work just as well, the compiler inserts the cast.


I had thought that division for any reason needed a floating point type variable. Maybe I'm thinking of another language. And if it was set up to result as a double literal, even if it was a whole number, that the compiler would complain, because it needs an int for the array index...
Steve Myers
Ranch Hand

Joined: Dec 08, 2012
Posts: 47
Jack Moore Iii wrote:
I had thought that division for any reason needed a floating point type variable. Maybe I'm thinking of another language. And if it was set up to result as a double literal, even if it was a whole number, that the compiler would complain, because it needs an int for the array index...


Division doesn't require floating point, but will truncate the fractional part if you cast to an int.

You're right in that the compiler will not allow you to store a double value in an int variable, but it would have to be cast to a double to complain, hence

will compile but will discard the fractional part but

or will not.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Exception handling and Recovery