Win a copy of Terraform in Action this week in the Cloud forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Rob Spoor
  • Bear Bibeault
Saloon Keepers:
  • Jesse Silverman
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • Al Hobbs
  • salvin francis

When to use Try and Catch

 
Ranch Hand
Posts: 77
2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi

It seems to me that try and catch should be used when there is an unknown external factor that can affect things, for example when getting input streams like from sockets or files etc. However, I have seen examples where programmers use it for validation of keyboard input which could easily be handled without try and catch. What is the correct use of try and catch. Also, what should be done when the catch block variables go out scope with the try block? Netbeans warns me to use try with resources but I don't understand that.

Advice appreciated!
Toni
 
Bartender
Posts: 369
44
Firefox Browser MySQL Database Java Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Try / catch is used to handle cases where an exception might be thrown but you don't want it to kill your program. It's used a lot in file IO, because most operations can throw exceptions (lots of things can go wrong with reading from or writing to a file). It will help you a lot to go through the Exceptions trail of the Java Tutorials.

Try with resources allows to open a resource (like a FileReader) in a try, and will automatically close it when it exits the try, regardless of whether an exception was thrown or not. It is covered in the Java Tutorials trail above, in the The try-with-resources Statement part.
 
Saloon Keeper
Posts: 24587
168
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You use try/catch when an Exception (or at least a Throwable) is likely to be thrown. You can't catch anything unless it has been thrown somewhere.

So the real question is when to use Exceptions, along with the age-old arguments of when to use checked versus unchecked Exceptions.

There is no hard and fast rule on that and different people will choose differently. The main thing to keep in mind is that Exceptions have a relatively high level of overhead, so they are best used for situations that are, well, exceptional.

Now the nice things about exceptions are that they can short-circuit a lot of logic that won't be needed in the instance of an exception and thus hopefully keep things a little tidier and a little more reliable. Also, an Exception can carry a complex payload, so that for example, instead of returning simply true or false from an XML parser depending on whether the input was good or not, you can return the exact line number and column number as well as a detailed description of what was wrong.
 
Saloon Keeper
Posts: 8770
71
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In theory Exceptions are supposed to be used for exception situations. Validating keyboard input does not usually fall into that category BUT the old stand-by was to return some designated value (e.g. -1) to indicate an error. This had a couple of problems: a) if the call should have returned an int then -1 might have been a legitimate value, b) what to do if the caller does not add code to handle an error. An answer to that had been to  throw an exception which forces developers to write code to deal with possible errors or risk having their programs crashed. A fairly recent alternative was the introduction of the Optional class which wraps the return value so that code must be written to get to the return value and, in the process, deal with any error conditions. That's the plan, anyway. One thing that I like about the exception approach is that it offers the  opportunity for the throw-er to create a message explaining why the exception is being thrown which the call-ee can use  in error messages. I also like that the call-er is forced to deal  with the issue or die.

Note that where an exception is caught is an important consideration. If you make a call that might result in an exception being thrown you should only catch it if there's something you can do about it or it influences the next step you need to take, otherwise let it percolate up the call chain.
 
Greenhorn
Posts: 2
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Generally, the ultimate goal of a programmer is to get correct output for the programs.

Just take a programming language like c, there is no concept of Exception Handling. So there may be chance of wrong output or abnormal termination of our program. And  there is another thing to remind is when our program terminates abnormally , the task is to find where we did the mistake in the program. This makes overhead.

But in Java programming language, there is a concept of Exception Handling. And java provides some built-in classes for Exceptions where different types of possible exceptions are defined. So it makes our programming easy also. By using this concept the programmer can make use of try and catch blocks to handle the abnormal termination of our program and also it is very easy to identify the mistake we did in the program by using this exception classes.

Many programmers use Exception handling(try, catch) for validating keyboard inputs. we can also validate the inputs without try, catch blocks. But as I mention earlier Java provides built-in classes for exceptions where different types of exceptions are defined, we can make use of them instead of writing validation code for keyboard inputs. It is easy to use try and catch blocks instead of writing extra code for validation.  In simple programs it may be easy to write code for validating keyboard inputs, but in complex applications it may be hard to handle such situations. So we can make use of the exception handling concept which is provided in java language.
 
Ranch Hand
Posts: 111
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Isn't using try/catch for user Input an "anti pattern" ?
 
Saloon Keeper
Posts: 1666
61
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Kevin O'Sullivan wrote:Isn't using try/catch for user Input an "anti pattern" ?



I am interested in seeing the opinions of respected posters here.

I certainly without doubt was taught that it was, but I came from a C++ world where there are/were a significant minority of skilled programmers who eschewed exceptions like the plague.

I believe their reasons were "You shouldn't pay for features you don't use, but if exceptions are used anywhere in a program, the whole program pays the cost!" or something like it.

I still say "Exceptions should be exceptional!  If there was some easy way you could avoid throwing and catching them, you should do that."

There's also a million places on the web that still say catching sub-classes of RuntimeException is an Anti-Pattern.  That those indicate you need to fix code or configuration and re-run...

It feels like whatever the balance of sides in Checked vs. Unchecked exceptions debates, that the world has pretty much given up on the distinction.

The input validation exceptions we are discussing here are "RuntimeException" classes, right?

When I first learned Java, there was definitely a sense that if you were catching those, you were engaging in exception abuse -- that seems to be less true now.
I guess because Checked Exceptions are a downright pain in the assembly?

 
Tim Holloway
Saloon Keeper
Posts: 24587
168
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Exceptions in C are much nastier than they are in Java. The only thing nastier was its predecessor: setjmp/longjmp. You can also throw anything in C++, including ints. There's no formal base class for exceptions there.

Nevertheless, in Java, just as in C. there's a fair amount of overhear in throwing and catching Exceptions, so no, it's not recommended to use them casually.
 
Jesse Silverman
Saloon Keeper
Posts: 1666
61
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Standard C didn't have exceptions, Windows-only people forget that because Microsoft provided the Structured Exception Handling -SeH options that made your C code totally non-portable right off the bat.

Yes, in C++ you can throw an int, a float, a char, a wchar_t or a Basoon or a Baboon...

While we were at it, I wanted to possibly complain about something in the Sybex 816 book.

They described a reason to make an Exception class to derive from RuntimeException rather than Exception (or similar or similar) how frequently or rarely you expected it.

Code that gets run lots will still have a lot of the rare things happen, so that approach doesn't scale for industrial designs, IMHO.

Back before we gave up on the distinction (or so it seems) between Checked and Un-Checked exceptions, I made the following different distinction:

RuntimeException sub-classes meant that the whole config of the run was wrong in a fatal way, or you had sloppy, reckless code that needed to be fixed.
Let it crash and if config-related give a good error message so the operator/user can fix it for re-run.  There is no recovering from this, your run is just hosed.
If you find yourself catching these except in a tutorial or on an interview, make sure your design makes sense...

Exception sub-classes were checked precisely because there was a reasonable likelihood of recovering from the problem somewhere up the call stack where you would catch it.  You didn't want the whole thread to die just because there was likely some action that could reasonably be taken up the call stack, and reasonably continue...

But like I said, it feels like the classical distinctions have been gradually melting away because everyone finds checked exceptions a pain in the butt.

 
Marshal
Posts: 26914
82
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Jesse Silverman wrote:The input validation exceptions we are discussing here are "RuntimeException" classes, right?



Yes, NumberFormatException, which can be thrown by Integer.parseInt(String), is a subclass of RuntimeException. Referring to the original post (and not the large quantity of tangential content following it), it mentions "validation of keyboard input". There's a lot of other situations where you might be given a String value and you want to convert it to a numeric (e.g. Integer) value, but let's just consider that. (You might be getting the data from a text file or a spreadsheet cell or an HTTP request or you name it.)

The original post says that this conversion "could easily be handled without try or catch". It's true that you could write some code which converts String to Integer without too much difficulty, although String to Double is considerably harder. But really. Why should the beginner with two days of Java learning under their belt be required to do that as part of writing their code which wants to get a number from the console? Just dealing with getting input from the console is enough to drive some beginners to drink. And so we have the parseInt and parseDouble and so on methods.

And of course when parsing a String value to a numeric value, you have to consider the possibility that there's going to be a problem because the input isn't a valid numeric value (for whatever "numeric" means in the current context). Languages without exceptions would have used various hacks to deal with that, but Java has exceptions built into the language and when exceptional situations occur then you should use exceptions to deal with them. This is in no way an anti-pattern, not in Java anyway. I don't see why errors in user input should be treated differently than errors with network connections or database queries.

But back to why NumberFormatException is a runtime exception, whereas FileNotFoundException is a checked exception: I have no idea why they did that -- as I just said or implied, I wouldn't have done it that way. Finding non-numeric data in Strings which are only supposed to contain numeric data is not a programming error, like using a null value where it shouldn't be found or using an array index which points outside the array. Those things can be checked simply by code and avoided, so they can be classified as programming errors, but checking data for numericness is not simple to do and it's not reasonable to expect the programmer to write code which does that.
 
Jesse Silverman
Saloon Keeper
Posts: 1666
61
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Paul Clapham wrote:

Jesse Silverman wrote:The input validation exceptions we are discussing here are "RuntimeException" classes, right?



Yes, NumberFormatException, which can be thrown by Integer.parseInt(String), is a subclass of RuntimeException....I don't see why errors in user input should be treated differently than errors with network connections or database queries.

But back to why NumberFormatException is a runtime exception, whereas FileNotFoundException is a checked exception: I have no idea why they did that -- as I just said or implied, I wouldn't have done it that way. Finding non-numeric data in Strings which are only supposed to contain numeric data is not a programming error, like using a null value where it shouldn't be found or using an array index which points outside the array. Those things can be checked simply by code and avoided, so they can be classified as programming errors, but checking data for numericness is not simple to do and it's not reasonable to expect the programmer to write code which does that.



b. I love your writing there (the whole thing).  It is eminently clear, focused and understandable.
a. the part I re-quoted above.  Yes, THAT.  Back at a time when I think the conceptual description of what is meant to be a checked exception and what is meant to be unchecked, in terms of coding/config errors vs. not-reasonable-to-prevent-yet-reasonable-to-retry-or-fix, that just doesn't make sense to me.  It falls into the "Don't Sweat It" category, but being a famous example that was already well known when I had learned that in general, catching RuntimeExceptions meant you didn't design your code well is just something that I don't get.  Maybe it is just one of the instances of "This is obviously wrong, but by the time we realized this it was too late to fix it without big repercussions -- we refuse to break working code!" that may be some people's favorite moments in the talks from the Core Java Guru's.  I love those, but also love when they point to little known examples of where one of two different equivalent ways of doing something in Java is way better than the other one, as sometimes there would be no reasonable way you would know that except studying their source code.  Those are great too.

Thanks, Paul!
 
Jesse Silverman
Saloon Keeper
Posts: 1666
61
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
At the risk of angering the Java Gods thru blasphemy, I will casually mention that C# seemed to consider throwing Exceptions for unexpected user input was a bit extreme.

When they got their chance to re-write stuff with their cheap knock-off of Java, they gave the user non-throwing options, but cheat by using an output parameter.

I will note that numerous people who code in more than three languages consider output parameters sub-standard design, others consider them extremely handy.

So whether this is bad or good is a matter of Style, Taste and Refinement, but C# chose that path instead:
https://docs.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-5.0

https://docs.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-5.0

https://docs.microsoft.com/en-us/dotnet/api/system.datetime.tryparse?view=net-5.0

I use those variants over the Java-style ones they also provide about 29 times out of 30 when programming in that "other language", they have some usage guidelines as to which one to pick:

https://docs.microsoft.com/en-us/dotnet/api/system.datetime.parse?view=net-5.0

Important

If the parsing operation fails because of an unrecognized string format, the Parse method throws a FormatException, whereas the TryParse method returns false. Because exception handling can be expensive, you should use Parse when the parsing operation is expected to succeed because the input source is trusted. TryParse is preferable when parsing failures are likely, particularly because an input source is not trusted, or you have reasonable default values to substitute for strings that do not parse successfully.

I will happily go months without referring to that other language, but felt that this addresses the original poster's question somewhat directly.

Because of intentional limits in the Java language compared to others we may use (no output parameters and no other easy language-level way to return multiple outputs from a message without a lot of fuss), it is not easy to write a Java version of a .parseWhatever() call that doesn't throw an Exception for unexpected input.  You could complicate the API by having two calls, which would entail two passes over the String, yuck!

On an interview where they would say I had to parse something and could not catch an exception -- how do I not crash, I certainly wouldn't write the conversion from scratch!  I would run out of time and get it wrong.

I would use:
https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/String.html#matches(java.lang.String)

and hope that I cooked up the RegEx to check it correctly while coding at high speed.

I have actually been asked to write a RegEx to validate a floating point number format as valid while standing there at a whiteboard in high heels and tiara during a coding interview.  I don't remember if I got it all right, but told them that if I had been switching languages recently, or hadn't code a RegEx for a few months, I would need to review stuff or just play around in RegExHero for a few minutes to be sure, but that it would look something like I had just written.

I would never bother doing this in Real Code.  I would just try { } catch the RuntimeException in Java...I think I also mentioned that since that job was in C# the question was unfair, because we don't need to do that there.  Everyone laughed and said "Good enough!"

Hey, I just realized that now that we have Optional since Java 8, it would actually be quite easy to write the equivalent API.  Just return an empty Optional<Whichever> in the case that Johnny can't parse that.  Of course, some people dislike Optional more than they dislike catching RuntimeException sub-classes, so, courses for horses.

It is a good interview question tho, methinks.

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
try-catch statements are used in Java to handle unwanted errors during the execution of a program.

Try: The block of code to be tested for errors while the program is being executed is written in the try block.
Catch: The block of code that is executed when an error occurs in the try block is written in the catch block.
The try block throws an Exception class object, which is caught by the catch block.
 
Marshal
Posts: 74390
334
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
SPS welcome to the Ranch

Don't say, “class object,” which is an ambiguous and inaccurate term.
 
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic