I'm writing a java program that adds two numbers with any length(the input is string). it works well but the judge gives me 44 because it has "Runtime Error" what should i do?
-
1catch the exceptions.SomeJavaGuy– SomeJavaGuy2015-12-04 09:46:16 +00:00Commented Dec 4, 2015 at 9:46
-
there is no exception,it works for all the numbersBob 22– Bob 222015-12-04 09:47:42 +00:00Commented Dec 4, 2015 at 9:47
-
So what are those runtime errors ?Arnaud– Arnaud2015-12-04 09:48:52 +00:00Commented Dec 4, 2015 at 9:48
-
i don't know .the console works perfectly .it gives no error in any kind. judge is the problemBob 22– Bob 222015-12-04 09:52:39 +00:00Commented Dec 4, 2015 at 9:52
-
Show the code you have, can't solve the problem if we can't see it.yitzih– yitzih2015-12-04 09:53:11 +00:00Commented Dec 4, 2015 at 9:53
|
Show 2 more comments
2 Answers
To Answer your question "How to handle runtime-errors",
It is not different from any other exception:
try {
someCode();
} catch (RuntimeException ex) {
//handle runtime exception here
}
This judge may have given you a 44 (assuming that is low) because the input that comes to you as strings may not be numbers at all, and if this happens, your program should not crash? That would be my guess
UPDATE: Now that you have some code up, this is most likely the case, what happens if String a is "hello" ? Your program would crash at Long.parseLong(), you need to handle this!
Comments
Replace all your calls to Long.parseLong, by calls to such a method :
private long checkLong(String entry){
long result = 0;
try
{
result = Long.parseLong(entry);
}
catch(NumberFormatException e)
{
System.out.println("Value " + entry + " is not valid") ;
System.exit(1);
}
return result;
}