I am trying to perform try and catch on a method parameter but I not able to do it and when the program is ran it gives me the error number format error instead of executing the code in catch block
Any help is appreciated. I am a beginner to java and programming. Thank you for taking the time to read my question.
public void inputCheck(int[] checkUserInput) {
try {
if (!(checkUserInput[1] <= 10 && checkUserInput[1] % 2 == 0)) {
errorMessage = "failEven";
} else if (checkUserInput[0] < 20 || checkUserInput[0] > 80) {
errorMessage = "failRange";
} else if ((checkUserInput[0] >= 20 || checkUserInput[0] <= 80)
&& (checkUserInput[1] <= 10 && checkUserInput[1] % 2 == 0)) {
errorMessage = "checkpassed";
}
} catch (NumberFormatException e){
System.out.println("Please enter an number");
}
}
Error message
Exception in thread "main" java.lang.NumberFormatException: For input string: "e"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at UserInput.promptUser(UserInput.java:27)
at MainClass.main(MainClass.java:11)
#
Your code doesn't throw any type of exception so catch block is not executed at all.
In simple terms, your code in try block is free from any type of run time error so your catch block is not reached at all. Catch block is only executed when your code in try block throws a exception.
The catch block handling a certain type of an exception is executed only when the code in a try block produces an exception of this type. Thus, your code in a catch could be executed only if the code in a try block throws NumberFormatException, but it doesn't. You have to either explicitly throw such an exception in a try block or call a method that could throw it.
try {
if (someCondition) {
throw new NumberFormatException();
}
} catch (NumberFormatException exp) {
System.out.println("Invalid format" + e.getMessage());
}
There is no need for the try and catch block here. Also the parameter is array of int, you cannot pass string for the parameter.
You can make use of the below, the second ASCII value will be consider.
int arr[] = {100,'e'};
Related
I have a method which uses proxies to retrieve information from a server. Sometimes due to a bad proxy I get SocketException, SSLException, SSLHandshakeException or ConnectException
I want the method to retry on the exceptions above, but on the IOException or no exception I want a string returned
Here is the method I constructed to test different scenarios
public String getTest(int i, int current, int total)
{
String text = "";
try
{
if (i == 1)
throw new IOException();
else if (i == 2)
throw new SSLException("SSLEx");
else if (i == 3)
throw new SocketException();
else
text = "EVERYTHING GOOD";
}
catch (SSLException | SocketException re)
{
if (current < total)
{
System.out.println("Recalling " + current);
getTest(1, ++current, total);
}
}
catch (IOException ioe)
{
text = "HTTP ERROR";
}
catch (Exception e)
{
e.printStackTrace();
}
return text;
}
I call my test method by
System.out.println(c.getTest(3, 0, 5));
Initially the program would catch a SocketException then retry by passing 1 so I can emulate a working proxy but a server response with IOException as i = 1 but the method never returns the text "HTTP ERROR"
What do I need to change in order for this to work as expected?
In order to return the string returned by your recursive function call, you must place return before the recursive function call like so...
return getTest(1, ++current, total);
Right now you are simply running the recursive function and discarding its return value. Your logic then returns your text string from the initial call (which in the case of an SSLException looks like an empty string).
You could also accomplish the same effect by assigning text from the recursive function...
text = getTest(1, ++current, total);
Both statements, considering the rest of your logic, are equivalent.
This question already has answers here:
Returning from a finally block in Java
(6 answers)
Closed 7 years ago.
Look at the code below. Although the catch clause itself throws an exception, the finally block's return statement causes that exception to be swallowed. This method will return 420 even if something goes wrong in the catch block.
private static int foo() throws Exception
{
try {
throw new Exception("try");
} catch (Exception ex) {
throw new Exception("catch");
} finally {
String s = "";
return 420;
}
}
You should return something else if you encounters an Exception. The exception is only dangerous if the variable that threw that exception is used in the final return statement. Consider this:
int a;
try{
//...
}catch(Exception e){
//a throws an exception somehow
}finally{
returns a;
}
And when you use a on the other side like this:
a += 1;
You get a dangerous exception.
My suggestion is to do this:
try{
//...
}catch(Exception e){
//a throws an exception somehow
returns -1;
}finally{
returns a;
}
And on the other side:
if(return_value == -1) // skip or do something else;
This way, you won't get a unpredicted exception on the other side.
Return in finally is a very bad idea. It doesn't hide only the exceptions you throw yourself, but also virtual machine errors such as stack overflow or out of memory errors. These errors can be thrown at any point, including when the key invariants of data structures don't hold, and it will be impossible to predict what the program will do.
In your case it is safe, but if we change your scenario a little
private static FileReader foo() throws Exception{
try {
throw new Exception("try");
} catch (Exception ex) {
throw new Exception("catch");
} finally {
return new FileReader("");//this may also throw something
}
}
Now, because we didn't specify proper path in your file system return new FileReader(""); will throw FileNotFoundException and we will lose exception thrown in catch section with new Exception("catch"); which is potentially dangerous.
Im trying to delete TXT-files, but I always get the same error message. It's nearly the same code as the one I found on the Internet.
for (int i = 0; i < datei.length; i++)
{
try
{
loeschenDatei = datei[i].delete();
if (loeschenDatei)
{
System.out.println(datei[i] + " wurde geloescht!");
}
else
{
System.out.println(datei[i] + " konnte nicht geloescht werden!");
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
I always get the error:
unreachable catch block for ioexception. this exception is never thrown from the try statement body.
This means that nothing within your try block can throw an Exception of type IOException. The only thing that I'm unsure of is datei[i].delete(). Check out that method signature in your IDE and see if at the end it throws IOException or something like that. If that method doesn't throw anything, then remove your try catch block altogether.
unreachable catch block for ioexception - compiler code validation is suggesting that. Possibly IO exceptions already handled in delete method.
In case you are unsure which exceptions may be thrown by your code, you could change IOException to Exception.
Sorry if my title is a little bit confusing.
My program is doing some web scraping and thus will catch a few SocketTimeoutException due to random network conditions. Right now when the SocketTimeoutException is caught, that particular loop is skipped, and therefore i will miss some data. I'm sure that everything will be fine when the code in the skipped loop is run again. As I'm scraping a huge amount of data ( > 1 million sets of numbers ), I don't want to record the exceptional loops and ran them again manually. Is there any way to run the same loop again when catch an exception?
try{
for(){
someCode
...
}
}catch(IOException){
}
Just put the try-catch inside the loop
for () {
try {
// somecode
// ..
} catch ( IOException ioException ) {
// handle
}
}
Why not put the exception handling inside the loop
for(){
try{
// someCode
}catch(IOException e){
//handle exception if necessary
}
}
You must be doing this. Do try catch inside the loop.
for(){
try {
someCode
...
} catch(IOException){
}
}
This has a problem,
try{
for(){
// someCode
...
}
}catch(IOException){
// Once exception happens your for() loop breaks !!!!!
}
Instead, do this...
for () {
try {
// somecode
// ..
} catch ( IOException ioException ) {
// handle(do something) here, not throwing error which will break the loop
}
}
I you want to redo the same loop iteration:
int i = 0;
int n = 15; // your n
for (i = 0; i < n; i++) {
try {
// some code
} catch (Exception e) {
i--;
}
}
But be careful of an infinite looping! You should add a MAX_TRIES management.
public KalaGame(KeyBoardPlayer player1,KeyBoardPlayer player2)
{ //super(0);
int key=0;
try
{
do{
System.out.println("Enter the number of stones to play with: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
key = Integer.parseInt(br.readLine());
if(key<0 || key>10)
throw new InvalidStartingStonesException(key);
}
while(key<0 || key>10);
player1=new KeyBoardPlayer();
player2 = new KeyBoardPlayer();
this.player1=player1;
this.player2=player2;
state=new KalaGameState(key);
}
catch(IOException e)
{
System.out.println(e);
}
}
when i enter an invalid number of stones i get this error
Exception in thread "main" InvalidStartingStonesException: The number of starting stones must be greater than 0 and less than or equal to 10 (attempted 22)
why isn't the exception handled by the throw i defined at
KalaGame.<init>(KalaGame.java:27) at PlayKala.main(PlayKala.java:10)
You are only handling an IOException but not the exception that is being thrown, i.e. an InvalidStartingStonesException.
You can catch multiple exception types and filter them accordingly:
try
{
// ...
}
catch(IOException ioe)
{
// ...
}
catch(Exception ex)
{
// ...
}
You could add this last catch block to match any exception.
It sounds like it is being handled by the throw. By calling throw, you are telling Java "exit the program and print out the InvalidStartingStonesException". It sounds like this is what is happening. If you had the following:
catch(InvalidStartingStonesException{
// code to handle the exception goes here
}
Then the program would run your error handling code. If this exception extended IOException you already have a catch there that would print the exception.
The catch(IOException) block does not catch the exception, because InvalidStartingStonesException is not an IOException, neither a descendant of it.
Your exception is an unchecked exception, just as IllegalArgumentException is. The compiler does not obligate the programmer to catch such exceptions, since they usually represent bugs and not situations that can be handled.
Since the exception is not being caught, it propagates all the way down in the call stack of the main thread, until your program terminates.