What is the complete process of try-catch in java? - java

I have been experimenting with try-catch and have been confused on specifically how it works.
try // x is array of 10 doubles set to 0
{
for (int a = 0; a < 11; a+= 2)
x[a] = 5;
}
catch(Exception e)
{
System.out.println("error");
}
In this instance, all values in the array can be reached, but the code breaks at x[10]. So, have all the values been set to 5?
try // x is array of 10 doubles set to 0
{
for (int a = -1; a < 11; a+= 2)
x[a] = 5;
}
catch(Exception e)
{
System.out.println("error");
}
In this instance, it will try x[-1] and catch the error. So, will it not go back and complete the loop (x[0], x[1], ... x[9] )? So, all values still remain 0?
Is this how the try-catch works?
Any help would be appreciated.
Thank you.

Yeah, both examples would throw ArrayIndexOutOfBoundsException.
So,
The try block contains a block of program statements within which an exception might occur. A try block is always followed by a catch block, which handles the exception that occurs in associated try block. A try block must followed by a Catch block or Finally block or both.
A catch block must be associated with a try block. The corresponding catch block executes if an exception of a particular type occurs within the try block. For example if an arithmetic exception occurs in try block then the statements enclosed in catch block for arithmetic exception execute.
try
{
//statements that may cause an exception
}
catch (exception(type) e(object))‏
{
//error handling code
}
If an exception occurs in try block then the control of execution is passed to the catch block from try block. The exception is caught up by the corresponding catch block. A single try block can have multiple catch statements associated with it, but each catch block can be defined for only one exception class. The program can also contain nested try-catch-finally blocks.
After the execution of all the try blocks, the code inside the finally block executes. It is not mandatory to include a finally block at all, but if you do, it will run regardless of whether an exception was thrown and handled by the try and catch blocks.

Try-Catch
The code within the try block is code that will run but if the code in the try block throws an exception/error then it is caught in catch block.
The issue with your code is you are using the x as an array and you may not be able to set a specific spot in an array, to set that you could do something like x.push or x.put I am not sure on the specific property as I do not know java well. The other issue could be that your index is out of bounds, which means that you may have an array of 10 items that is zero based and you are trying to access an 11th item. so your loop should be something like:
{
for (int a = 0; a < x.length; a+= 2)
x[a] = 5;
}

When a statement throws an exception inside of a try block, the next statement is the first statement of the catch block.
In the first example, the first few iterations of the for loop happen as normal and elements 0, 2, 4, 6, and 8 are set to 5. On the iteration where a is 10, the attempt to access x[10] the runtime throws an ArrayIndexOutOfBoundsException and jumps to the first statement of the catch block. The rest of x is unmodified.
In the second example, the first iteration of the for loop causes the runtime to throw an ArrayIndexOutOfBoundsException (due to the attempt to access x[-1]) and jump to the first statement of the catch block. The effect is that x is completely unmodified.
For more information about exceptions in Java, read the The Java Tutorials: Exceptions.

Related

java question about try catch statement with finally [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
Here is a code written by java.
public class work2{
public static void main(String args[]) {
try {
int x = 0;
for (x=1; x<4; x++);
System.out.println(x);
} catch(Exception e) {}
finally {
System.out.println("Error");
}
}
}
And the output is
4 Error
Would you explain why the output is looks like this?
Always remember in a try catch block - "finally always Run", irrespective of whether there is an exception or not. Now coming to your code. Inside the try block you have below line:
try {
int x = 0;
for (x=1; x<4; x++);
System.out.println(x);
}
Here the for loop ends in a semicolon, which means it doesn't have a body.
Now, the for loop will run from i=1 till i<4 and then will come out of loop with value of i as 4.
Now the next line is a print statement which prints the current value of i as 4.
After that the controls goes to the finally block and prints "Error"
That's how you get the output as
4
Error
The for - Loop you're using is only increase the value of x but doesn't print it out. So you increase x to 4 and than print it out, the finally part will be printed anyway.
If you want to put out every value of x, you had to add { } after the for - Loop.
It will look like:
public class Main{
public static void main(String args[]) {
try {
int x = 0;
for (x=1; x<4; x++) {
System.out.println(x);
}
} catch(Exception e) {}
finally {
System.out.println("Error");
}
}
}
try {
int x = 0;
for (x=1; x<4; x++);
System.out.println(x);
}
the try block didn't catch any exception, so the code were run as it is.
and in
finally {
System.out.println("Error");
}
A finally block contains all the crucial statements that must be
executed whether exception occurs or not. The statements present in
this block will always execute regardless of whether exception occurs
in try block or not such as closing a connection, stream etc.
it will print "Error" regardless what happen.
So, Try block printed 4, and then Finally block print "Error"
You write the statements which cause exception in try block. And these exceptions are handled using catch block. finally block is executed even if exception is not triggered.
In your question, x=0; initially. Since there is a semicolon ; after for loop, the loop will be executed 3 times and when x=4, the condition fails and it prints the value of x that is 4. And finally block is executed.
public class Main{
public static void main(String args[]) {
try {
int x = 0;
for (x=1; x<4; x++)
System.out.println(x);
} catch(Exception e) {}
finally {
System.out.println("Error");
}
}
}
The output should be
1
2
3
error
you should remove the ; after for loop .
A finally block contains all the crucial statements that must be executed whether exception occurs or not. ... The statements present in this block will always execute regardless of whether exception occurs in try block or not such as closing a connection, stream etc.

Will modifications to a function's return value in the finally block take effect? [duplicate]

This question already has answers here:
Why does changing the returned variable in a finally block not change the return value?
(7 answers)
What happens if a finally block modifies the value returned from a catch block? [duplicate]
(2 answers)
Closed 2 years ago.
Consider the following code:
int dummy() {
int x = 0;
try {
x = x + 1;
throw new Exception();
} catch (Exception e) {
x = x + 2;
return x;
} finally {
x = x + 4;
}
I need to "predict" the behaviour of this method without programming it. My question is, what will the return value be?
My guess would be that when an exception occurs, the finally block will be realized, so the value of x will be 4. But I think the value will not be returned. And if no exception occurs, the value will be 2 and it will be returned.
I'm a complete beginner (less than 3 months) in programming so I might be missing something.
The following things will happen when you will call this method:
The expression, x = x + 1; will increase the value of x by 1 i.e. its value will become 1. Then, throw new Exception(); will be executed and as a result, the control will enter the catch block.
Inside the catch block, x = x + 2; will increase the value of x by 2 i.e. its value will become 3 which is the value that will be returned.
Since finally block is supposed to be executed irrespective of whether an exception is thrown or not, this block will be executed but it won't change the return value. Thus, finally block is useless here. Typically, finally block is used to release resources. Check this to learn more about it.
First, your int x is declared at 0.
You enter the try block and x becomes 1.
An Exception is thrown, hence the control moves to the catch block.
Here, x gets 2 more and goes to 3, then the value 3 is ready to be returned.
However, the execution continues to execute the finally block and x = x + 4 -> 7 but this doesn't change your return value since when you return an int you're passing its value, not the reference of the variable x.
If you want to know more, I'm sure who assigned you this puzzle will be glad to help!

Selenium and Java: While loop not working as expected

I have a challenge with automating a click action and I'm struggling to understand what's wrong with the logic in my solution.
My challenge is that I need to click one of a number of different radio buttons.
Each radio button has an id of "r" + a_number.
I don't know, for any given test, what the available "r" + a_number options there will be, so I wrote this while loop, which is intended to click the first available radio button:
int counter = 0;
while(true) {
counter++;
try {
driver.findElement(By.id("r" + counter)).click();
} catch (NoSuchElementException e) {
continue;
}
break;
}
This isn't working as intended - could someone help me understand what's wrong?
Note: I'm a novice with Java
Update
My aim is to click the first existing radio button, so the while loop increments the counter var, let's say r=1, then attempts to click a radio button with id "r1". If there is no such element with id "r1", a NoSuchElementException is thrown, in which case the current while loop iteration should stop and start the next iteration (r = 2, try to click element "r2", if does not exist, start next while loop cycle).
Suppose we get to element "r20" and this element does in fact exist, then the button should be clicked, the exception is not thrown and so the while loop continues and hits the break command, and the while loop is terminated.
The current behaviour, however, is that the exception does not get handled even when the element does not exist, the while loop terminates, but nothing has been clicked.`
There are two issues with the code:
Loop running only once- You are breaking the loop using break statement, after the first iteration itself.
No exception thrown- You are not logging the exception. You are only executing a 'continue' statement in the catch block. You do not need the statement because the loop will go to next iteration anyway (well after you remove the break statement).
You should use this code:
int counter = 0;
boolean foundElement = false;
while(!foundElement) {
counter++;
try {
driver.findElement(By.id("r" + counter)).click();
foundElement = true;
} catch (NoSuchElementException e) {
//assuming you want to log exception. Otherwise you can leave the catch block empty.
System.out.println(e);
}
}
Not sure and may need little more information however, I would do it little differently
int counter = 0;
boolean ifNotFound = true;
while(ifNotFound) {
counter++;
try {
driver.findElement(By.id("r" + counter)).click();
ifNotFound = false;
} catch (NoSuchElementException e) {
System.out.println("exception caught");
}
}
I am just trying to click and if it is successful then will set the while loop to false and it will break.
It may be possible that the exception you are catching is not the one is being thrown so you may try to change it to generic Exception and if that works then you can catch more specific one or more than one if you need to.
Please use this:
int counter = 0;
while(true) {
counter++;
boolean elementFound = false;
try {
driver.findElement(By.id("r" + counter)).click();
elementFound = true;
} catch (NoSuchElementException e) {
continue;
}
if (elementFound){
break;
}
}

Java: Running potentially blocking code

I am developing a small game, (Java, LibGdx) where the player fills cloze-style functions with predefined lines of code. The game would then compile the code and run a small test suite to verify that the function does the stuff it is supposed to.
Compiling and running the code already works, but I am faced with the problem of detecting infinite loops. Consider the following function:
// should compute the sum of [1 .. n]
public int foo(int n) {
int i = 0;
while (n > 0) {
i += n;
// this is the place where the player inserts one of many predefined lines of code
// the right one would be: n--;
// but the player could also insert something silly like: i++;
}
return i;
}
Please note that the functions actually used may be more complex and in general it is not possible to make sure that there cannot be any infinite loops.
Currently I am running the small test suite (provided for every function) in a Thread using an ExecutorService, setting a timeout to abort waiting in case the thread is stuck. The problem with this is, that the threads stuck in an endless loop will run forever in the background, which of course will at some point have a considerable impact on game performance.
// TestClass is the compiled class containing the function above and the corresponding test suite
Callable<Boolean> task = new Callable<Boolean>() {
#Override
public Boolean call() throws Exception {
// call the test suite
return new TestClass().test();
}
};
Future<Boolean> future = executorService.submit(task);
try {
Boolean result = future.get(100, TimeUnit.MILLISECONDS);
System.out.println("result: " + (result == null ? "null" : result.toString()));
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
future.cancel(true);
}
My question is now: How can I gracefully end the threads that accidentally spin inside an endless loop?
*EDIT To clarify why in this case, preventing infinite loops is not possible/feasable: The functions, their test suite and the lines to fill the gaps are loaded from disk. There will be hundrets of functions with at least two lines of code that could be inserted. The player can drag any line into any gap. The effort needed to make sure no combination of function gap/code line produces something that loops infinitely or even runs longer than the timeout grows exponentially with the number of functions. This quickly gets to the point where nobody has the time to check all of these combinations manually. Also, in general, determining, whether a function will finish in time is pretty much impossible because of the halting problem.
There is no such thing as "graceful termination" of a thread inside the same process. The terminated thread can leave inconsistent shared-memory state behind it.
You can either organize things so that each task is started in its own JVM, or make do with forceful termination using the deprecated Thread.stop() method.
Another option is inserting a check into the generated code, but this would require much more effort to implement properly.
The right way is to change the design and avoids never ending loops.
For the time being, inside your loop you could check if the thread is interrupted some way by: isInterrupted() or even isAlive().
And if it is you just exit.
It is not normal to have a never ending loop if it not wanted.
To solve the problem You can add a counter in the loop and if you reach a limit you can exit.
int counter = 0;
while (n > 0) {
counter++;
if (counter > THRESHOLD) {
break;
}
i += n;
// this is the place where the player inserts one of many predefined lines of code
// the right one would be: n--;
// but the player could also insert something silly like: i++;
}

Filing labels with color

I have Grid of labels (size n*n) and I want to fill with color its irregular part. I wrote a method
private void fill(int j){
while(board[j].getName().equals("s")){
board[j].setBackground(Color.yellow);
try{
fill(j-1);
} catch (ArrayIndexOutOfBoundsException e){}
try{
fill(j+1);
} catch (ArrayIndexOutOfBoundsException e){}
try{
fill(j+n);
} catch (ArrayIndexOutOfBoundsException e){}
try{
fill(j-n);
} catch (ArrayIndexOutOfBoundsException e){}
}
}
and I'm still getting StackOverflowError. I'm not using big parts (my n is max 20), I've tried to replace while with if, but didn't work too. Is it too big for a stack or might be there infinite loop? How I can fix that?
Lets say that for some reason for
j and j-1 condition in while will are satisfied,
for rest values like j-2 not
So if you invoke fill(j) program will
test while condition for j (pass)
enter while loop
setBackground for j
invoke fill(j-1);.
Now before program will invoke fill(j+1), program will have to finish fill(j-1) so flow of control will be moved to fill(j-1) level and program will
test while condition for j-1 (pass)
you enter while loop
setBackground for j-1
invoke fill((j-1)-1); in other words fill(j-2).
And again before fill((j-1)+1) flow of control will be moved to fill(j-2) so program will
test while condition for j-2 (fail)
program cant enter loop so will return return from fill(j-2)
invoke fill((j-1)+1) which is the same as fill(j)
So your application will try to repeat the same scenario, but this time on different stack level which will lead to StackOverwlow.
To prevent this situation maybe change condition to also test if you already been at this position, like
while(board[j].getName().equals("s") && board[j].getBackground() != Color.yellow)
You can/should also change while to if.
board[j].setName("bgSet")
after
board[j].setBackground(Color.yellow)
this might solve the problem, otherwise your while is always true.

Categories