java question about try catch statement with finally [closed] - java

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.

Related

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!

How to have a break of a few seconds in execution of program [duplicate]

This question already has answers here:
I get exception when using Thread.sleep(x) or wait()
(13 answers)
Closed 6 years ago.
This question might sound strange but I'm interested to know if somehow i can have a break of a few seconds in execution of a program.For example when you have a simple for() for printing out the elemnts of an array,the elements will be printed all directcly.I was wondering if it is possible to print like the first element then after a break of 2 second print the second one and so on until the last one.Is something like this possible?
Just add the Thread.sleep().
for (...) {
//print the element
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
//do things with exception
}
}
You can with the function sleep .
Thread.sleep(4000); // 4000 = 4 second
I recommend to use Thread.sleep()
Try this :
try {
Thread.sleep(1000);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
In this way, the program will pause for 1000 milliseconds.
You can use Thread.sleep(1000) method in for loop:
public class JavaApp{
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.println(i);
try {
Thread.sleep(1000);
} catch (Exception e) {
}
}
}
}
It prints from 0 to 9, one number per second.
run:
0
1
2
3
4
5
6
7
8
9
**BUILD SUCCESSFUL (total time: 10 seconds)**
Thread.currentThread.sleep(time in ms);

What is the complete process of try-catch in 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.

Java Thread.sleep inquiry

So I was wondering if there was anyway I could implement this code so that it pauses on each loop iteration. Currently, when I run the code, the program will stop for n seconds (n being the amount of loop iterations) and then display everything at once. However, I wish for it to display one item, wait one second and display the next item. I hope this is clear.
while(x > 0 || y > 0){
Try{
Thread.sleep(1000);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
// Print x and y
//Change x and y vals
}
}
First, don't suppress InterruptedException. If there's nothing to be done about it, simply don't catch it at all, or convert it into a RuntimeException e.g.
throw new RuntimeException(ie);
Second, it sounds like you're describing a flushing problem, which can be addressed by adding calls to:
System.out.flush();
After you print your values. As mentioned in the linked question however, System.out and System.err auto-flush whenever a new line is printed; are you not printing to stdout, or not printing new lines?
You should have a Thread.sleep() call wherever you need the program to pause, so if you need to pause between printing x and y, add another Thread.sleep() between them.
Suggestion: separate the thread sleep in a method to do the job without rewriting all this code.
Suggestion 2: search aroung if thread sleep is the best solution for you
Try this:
public void waitSeconds(int seconds){
try{
Thread.sleep(seconds*1000l);
} catch(Exception e) {
e.printStackTrace(); //ugly but enough to explain
};
}
public void yourMethod(){
while(x > 0 || y > 0){
waitSeconds(1);
print x
waitSeconds(1);
print y
//Change x and y vals
}
}
It's really strange. Try this way:
while(x > 0 || y > 0) {
// Print old values
// Change your x and y
// Print new values
try {
TimeUnit.SECONDS.sleep(y);
} catch(InterruptedException ex) {}
}

int[] total not printing [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 8 years ago.
Improve this question
I'm sorry if this title isn't descriptive; it's hard to explain the problem without the code. My problem is this: I'm running this code
private static Integer[] buffer = new Integer[60];
private static int sum;
...
public static void main(String[] args) throws InterruptedException{
...
while (true) {
try {
main.repaint(); //call paint() method for graphics
rebuffer();
getBufferSum();
//System.out.println(sum);
} catch (NullPointerException e) {}
Thread.sleep(1000);
//}catch(NullPointerException e){e.printStackTrace();}
}
}
private static void getBufferSum() {
System.out.println("Started");
int total = 0;
for(int i = 0; i < 60; i++){
total += buffer[i];
}
System.out.println(total);
sum = total;
}
private static void rebuffer() {
for(int i = 1; i < 60; i++){
buffer[i - 1] = buffer[i];
}
buffer[59] = count;
//System.out.println(count);
count = 0;
System.out.println("Done");
}
And I'm getting this output:
Done
Started
Done
Started
Done
Started
...
Why is the line System.out.println(total); failing to execute?
Your buffer variable is an array of Integer, which is nullable (contrary to primitive int, which defaults to 0).
It's likely that any element has not been initialized before invoking them by index in your getBufferSum method, hence a NullPointerException that is not logged, hence a sleeping time of 1 second, hence the "Done" statement prints thereafter.
You should probably add e.printStackTrace(); in your catch statement to figure this out, instead of sleeping for 1 second.
Also consider debugging your code.
As Hovercraft Full Of Eels points out, it is considered very bad practice to catch NullPointerExceptions (as most RuntimeExceptions and all Errors).
On the long run you should get rid of that try / catch.

Categories