0

While working on a code, I was wondering if I could avoid try n catch and used something else. For example, if i have a value(from console) of type double and if user enters a string or something else then there should be a prompt to re-enter the value.

I know this can be done very easily using try-n-catch but how can we do it without it, is there any way out?

Please give an example if possible.

4
  • 3
    What's the problem with the question? Throwing exceptions is expensive. The question is asking how to avoid getting exceptions thrown when parsing invalid values. (I would agree if the question were generally about coding without using exceptions, but the text is clear about the specific use-case, which is perfectly valid.) Commented Aug 25, 2013 at 16:29
  • Are you asking about the wisdom if avoiding try/catch in general or the specific case of parsing a double from a string? Commented Aug 25, 2013 at 16:33
  • 1
    I wouldn't recommend handcoding double validation. It's quite a roundabout way of second-guessing parseDoubles result, and it's complex. There's scientific notation, four different limits to check, ... Commented Aug 25, 2013 at 16:34
  • i am wondering, if I could use hasNext to validate the double input. Please advise! Commented Aug 25, 2013 at 16:57

2 Answers 2

8

Sadly, the JDK lacks the TryParse method that some other libraries provide. I wouldn't be surprised to find something in Apache Commons or Guava that does it.

Alternately, you might use a Scanner and use its hasNextDouble to do the check.


If you're asking how to avoid dealing with exceptions in general: Don't try. Exceptions are a powerful way of handling exceptional conditions in programs, and the "handle-or-declare" provided by checked exceptions (e.g., your code must handle the exception, or declare that it doesn't) is very useful.

But there are some use-cases, like your example, where you might well want to avoid an exception being thrown because, after all, a user entering invalid input isn't an exceptional condition, it's an all-too-common one. :-)

Sign up to request clarification or add additional context in comments.

Comments

1

Throw Exceptions are less robust but a good way to deal avoiding with try/catch statements.

 import java.io.*;

 public class UsingThrows { 
 public static void main(String args[]) throws FileNotFoundException { 

 FileInputStream fis = new FileInputStream("def.txt");
 System.out.println("OK 1"); 

  }
 } 

1 Comment

this is a good way indeed but i don't want to use exceptions at all, any other alternative?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.