I am trying to write a try catch block like the following, but put it inside a loop. My issue is that when i put it in a while loop, it runs x amount of times. i want it to stop when the first try is successful. but give the option to run up to 3 times.
try {
myDisplayFile();
} catch (FileNotFoundException e1) {
System.out.println("could not connect to that file..");
e1.printStackTrace();
}
public static void myDisplayFile() throws FileNotFoundException{
Scanner kin = new Scanner(System.in);
System.out.print("Enter a file name to read from:\t");
String aFile = kin.nextLine();
kin.close();
Scanner fileData = new Scanner(new File(aFile));
System.out.println("The file " + aFile + " contains the following lines:");
while (fileData.hasNext()){
String line = fileData.next();
System.out.println(line);
}//end while
fileData.close();
}
int max_number_runs = 3;
boolean success = false;
for( int num_try = 0 ; !success && num_try < max_number_runs ; num_try++ )
{
try
{
/* CODE HERE */
success = true;
}
catch( Exception e )
{
}
}
int someCounter = 0;
boolean finished = false;
while(someCounter < 3 && !finished) {
try {
//stuff that might throw exception
finished = true;
} catch (some exception) {
//some exception handling
someCounter++;
}
}
You can break; within a try catch block and it will exit the loop that it's in (not just the try catch block), but from a readability stand point, this posted code might be better.
finished = true should be the final line of the try block. It won't throw an exception. And it will only execute if every other line of the try block executed without an exception. So if you get to finished = true, you didn't throw and exception, so you can toggle your flag and exit the loop.
Otherwise, if an exception is thrown, the finished = true; line won't execute. You'll deal with the exception, then increment the someCounter++ variable.
This is ideal from a readability standpoint because all possible while loop exits are marked in the conditional part of the while loop. The loop will continue until either someCounter is too large, or finished returns true. So if I'm reading your code, all I have to do is look through your loop for the parts where these variables are modified, and I can quickly understand the loop logic, even if I don't yet understand everything the loop is doing. I don't have to hunt for break; statements.
I hope I understood your problem correctly. Here's a way.
int noOfTries = 0;
boolean doneWithMyStuff = false;
final int MAX_LOOP_VAL = 10;
int noOfLoops = 0;
while(noOfTries < 3 && noOfLoops < MAX_LOOP_VAL && !doneWithMyStuff) {
try {
// Do your stuff and check success
doneWithMyStuff = true;
}
catch (Exception e) {
noOfTries++;
e.printStackTrace();
}
finally {
// Close any open connections: file, etc.
}
noOfLoops++;
}
Related
I am trying to set up a program that uses a thread to write to an array from a BufferedReader, and another to read from it.
However, if the read result is null (i.e. read index is ahead of write index), I want it to wait, then access the same index again.
I've tried using synchronized statements and read() and notify() like this.
int n = Integer.parseInt(br.readLine());
String[] lines = new String[n];
Thread t1 = new Thread(() -> {
try {
for (int i = 0; i < n; i++) {
synchronized(lines) {
lines[i] = br.readLine();
lines.notify();
}
}
} catch (IOException e) {
return;
}
});
t1.start();
Thread t2 = new Thread(() -> {
try {
int i = 0;
while (i < n) {
String get = lines[i];
if (get == null) {
synchronized (lines) {
lines.wait();
}
continue;
}
add(representString(lines[i]), hmap);
i++;
}
} catch (InterruptedException e) {
e.printStackTrace();
return;
}
});
t2.start();
Problem is, I have a suite of tests that would sometimes freeze, but sometimes work. (I don't have a background in multithreading, I'm just learning from online tutorials to do a non-concurrency assignment faster.)
I made a method which purpose is to delete list of questions. The method Test contains questions, answers, number of questions, points. And works fine.
I get the following error:
Unreachable statement on : System.out.println("The test \"" + tests[indice - 1].getNomTest());
Here is the code:
public static int supprimerTest(Test[] tests, int nbrTests) {
int longueurTests = tests.length;
int indice = 0;
int noTest = 1;
int saisieNoTest = 0;
String nomTest;
System.out.println("***DELETE A TEST***\n");
if (nbrTests > 0) {
boolean fin = true;
do{
System.out.print("Please enter a number of the question to be deleted");
try {
indice = Clavier.lireInt();
if (indice < 1 || indice > nbrTests){
throw new IndexOutOfBoundsException();
System.out.println("The test \"" + tests[indice - 1].getNomTest());
tests[indice-1] =null;
nbrTests--;
fin = false;
}
}catch (Exception e) {
if (nbrTests < 1){
System.out.print("ERROR ! the number must be between 1 and " + nbrTests + "try again...");
}else {
System.out.println("ERROR ! the number must 1. ... Try again...");
}
}
}while (fin);
}else {
System.out.println("Il n'existe aucun test.");
System.out.print ("\nTPress <ENTRER> to continue ...");
Clavier.lireFinLigne();
}
return nbrTests;
}
Thank you for your help.
The reason you have that error is because exceptions act similar to a return statement where it'll get caught by the nearest Exception handler.
Since you have:
throw new IndexOutOfBoundsException();
Any code underneath that throw will never be reached because it immediately jumps to your catch block.
I hope that makes sense. :)
When you use try statement, it throws exceptions automatically if it is being detected. Therefore, simply take out the throw exception line, then your code should work.
When you throw an exception, the code below the throw will be not executed. Throw invoke exception and the method can continue only in catch/finally block. Lines after throw new IndexOutOfBoundsException(); cannot be reached. Maybe your code should be following:
if (indice < 1 || indice > nbrTests){
throw new IndexOutOfBoundsException();
}
System.out.println("The test \"" + tests[indice - 1].getNomTest());
tests[indice-1] =null;
nbrTests--;
fin = false;
I tried to re-execute a method specified number of times when exception occurs in a method,
but I am unable re-execute the method
int maxretries=10;
void show(){
try{
display();
}
catch(Exception e)
{
for(int i=1;i<maxretries;i++){
display();//on first retry only I am getting exception
}
}
}
when I run the code it is executed for first retry and I am getting exception but I want to reexecute display() method upto it is excuted successfully with in maximum retries.
The call you coded inside the catch is not inside a try, so it will not catch exceptions.
You need to use other concepts to do this, either calling the whole function again, or coding a successive try block inside the catch (and a further try block inside that catch block, etc.), or coding the loop around the whole try block (probably the best approach).
What about this:
int maxretries = 10;
for (int i = 0; i < maxretries; i++) {
try {
display();
break;
} catch (Exception e) {
// log exception
e.printStackTrace();
}
}
In below program I am executing rerun method specified number of times even though exception occured with 5 sec time gap.
public class ReExecuteMethod {
public static void main(String[] args) throws Exception {
int count = 0;
while (count <= 10) {
try {
rerun();
break;
} catch (NullPointerException e) {
Thread.sleep(5000);
System.out.println(count);
count++;
}
}
System.out.println("Out of the while");
}
static void rerun() {
// throw new NullPointerException();
System.out.println("Hello");
}
}
Here are my codes.
try{
if("**".equals(state[i][j-1])){
state[i][j-1] = String.valueOf(stopState);
stopState++;
willBeInitialized[i][j-1] = true;
}
if("**".equals(state[i+1][j-1])){
state[i+1][j-1] = String.valueOf(stopState);
stopState++;
willBeInitialized[i+1][j-1] = true;
}
if("**".equals(state[i+1][j])){
state[i+1][j] = String.valueOf(stopState);
stopState++;
willBeInitialized[i+1][j] = true;
}
if("**".equals(state[i][j+1])){
state[i][j+1] = String.valueOf(stopState);
stopState++;
willBeInitialized[i][j+1] = true;
}
if("**".equals(state[i-1][j+1])){
state[i-1][j+1] = String.valueOf(stopState);
stopState++;
willBeInitialized[i-1][j+1] = true;
}
if("**".equals(state[i-1][j])){
state[i-1][j] = String.valueOf(stopState);
stopState++;
willBeInitialized[i-1][j] = true;
}
}catch(Exception a){
//continue next if statements;
}
What should I write in the catch scope?
Or whether I should rewrite the statement? And how?
The simple answer is, you don't; if you want an exception in one part of the code to not cause another part to be skipped over, you have to put them in different try blocks. In your case, however, there is an elegant solution, looping to represent many different try blocks with a single block of code:
for (int k = i - 1; k <= i + 1; k++) {
for (int l = j - 1; l <= j + 1; l++) {
if (l - j == k - i) continue;
try {
if("**".equals(state[k][l])){
state[k][l] = String.valueOf(stopState);
stopState++;
willBeInitialized[k][l] = true;
}
} catch (Exception e) {
//do nothing, loop to next try block
}
}
}
I would kindly suggest to rewrite your code with less repetition. You keep checking for the same condition in different cells of state array. So I would suggest something like this:
for(k=i-1;k<i+1;k++){
for(l=j-1;l<j+1;l++){
try{
if("**".equals(state[k][k])){
state[k][l] = String.valueOf(stopState);
stopState++;
willBeInitialized[k][l] = true;
}
}catch(Exception e){
//Even if you get an exception while the if statement is evaluated,
//the loop will continue to execute the next if snippet
continue;
}
}
}
Of course I cannot guarantee that this is the snippet you need, but I think you get the logic I propose.
Hope I helped!
I just started to learn Java, so have a lot of questions. And now I need to return to the beginning of program if a problem occurs.
public static int getchartoint() throws IOException {
int a;
try {
BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in));
String k = bReader.readLine();
a = Integer.parseInt(k);
return a;
}
catch (NumberFormatException exc) {
System.out.println(exc);
return a = 0;
}
finally {
}
}
and I have a = 0, I could write case in main() body:
case 0: {
System.out.println("Your entered an incorrect number...");
}
My question is: how can I add a line that moves me to exactly that line of code?
Call the "getchartoint" method before your switch/case statements.
Then when it returns integer 0 it will execute the case statement.
It looks like you just want to return 0; instead of return a=0;.