Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I think this is correct... When an exception occurs an object of the exception class is thrown and if we dont use a try or catch block, then the object goes to the JVM.
My question is why is the try block necessary, why wouldn't a catch block be good enough since the exception object is not created in the try block? I know that java requires you to use a try block to test the code in which the exception might occur, but was wondering if the exception object is created either way, then why couldn't a catch block been sufficient enough. This question is different from other exception handling questions in that it doesn't appear anyone has asked about needing to have the try block specifically.
The try { } portion indicates the section of code the catch { } block is protecting.
void test() {
do_something(); // Not covered
try {
something_fixable(); // Covered
} catch (InvalidStateException ex) {
do_recovery_for_fixable_thing();
}
}
Without the try { } block, the catch { } block might try to catch an exception other than the one it can handle.
Even if the exception thrown by do_something() is the same kind of exception, an InvalidStateException, the recovery code won't handle it; it isn't supposed to.
Suppose you had the following
doSomething(); // throws Exception1
doNothing(); // throws Exception2 which extends Exception1
catch(Exception 1 ex){ // handle exception }
To what does the catch block apply? Will it act only if an exception is thrown in doNothing()? Or will it also apply to the call to doSomething(). Or perhaps it will only apply to doSomething() and not doNothing(), which throws Exception2.
There is precedent for the omission of brackets. For example consider the next 2 groups of code.
int i;
for( i = 0 ; i < 10 ; i++)
System.out.println("hello World" + i);
and
int i;
for( i = 0 ; i < 10 ; i++)
{
System.out.println("hello World" + i);
}
Here the for statement is understood to act either on the next bracketed block or next single line of code.
So I suppose it might have been possible to have catch statements work on the previous statement or on the previous block. But that is just syntactic sugar, right? There is no functionality that you lose by requiring a try block.
Related
This question already has an answer here:
Why does the execution order between the printStackTrace() and the other methods appear to be nondeterministic?
(1 answer)
Closed 7 years ago.
I am trying to understand how the try-catch-finally execution flow works. There are a couple of solutions from Stack Overflow users regarding their execution flow.
One such example is:
try {
// ... some code: A
}
catch(...) {
// ... exception code: B
}
finally {
// finally code: C
}
Code A is going to be executed. If all goes well (i.e. no exceptions get thrown while A is executing), it is going to go to finally, so code C is going to be executed. If an exception is thrown while A is executed, then it will go to B and then finally to C.
However, I got different execution flows when I tried it:
try {
int a=4;
int b=0;
int c=a/b;
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally {
System.out.println("common");
}
I am getting two different outputs:
First output:
java.lang.ArithmeticException: / by zero
at substrings.main(substrings.java:15)
lication.AppMain.main(AppMain.java:140)
common
However, when I ran the same program for the second time:
Second output:
common
java.lang.ArithmeticException: / by zero
at substrings.main(substrings.java:15)
What should I conclude from this? Is it going to be random?
printStackTrace() outputs to standard error. System.out.println("common") outputs to standard output. Both of them are routed to the same console, but the order in which they appear on that console is not necessarily the order in which they were executed.
If you write to the same stream in both catch block and finally block (for example, try System.err.println("common")), you'll see that the catch block is always executed before the finally block when an exception is caught.
Exception's printstacktrace() method source code(defined in Throwable class)
public void printStackTrace() {
printStackTrace(System.err);
}
The formatting of output occurs because your are using standard output stream through System.out.printlnand exception occurs System.err stream
Try having a variable which will check exceptions and print in same error console if exception occurs :-
boolean isException = false;
try {
int a=4;
int b=0;
int c=a/b;
}
catch (Exception ex)
{
isException = true
ex.printStackTrace();
}
finally {
if(isException){
System.err.println("common");
}else{
System.out.println("common");
}
}
This question already has answers here:
Multiple returns: Which one sets the final return value?
(7 answers)
Closed 8 years ago.
I was going through a couple of questions that are often asked in job interviews (at least in my country - Switzerland), and I was quite unsure about the output of a block of code that is supposed to be tricky. It would be nice to hear what you think the correct answer is.
here it is :
 public class LanguageTest12 {
public static void main(String... args){
System.out.println(foo());
}
private static int foo() {
int a = 1, b = 2;
try {
return a+b;
} finally {
a = 10;
b = 20;
return a+b;
}
}
}
I know however that the answer must be one of those three possibilities :
3
30
33
(PS: just in case someone is interested, here are the all the questions : http://se.inf.ethz.ch/courses/2014a_spring/JavaCSharp/exercise_sessions/ExerciseSession5.pdf)
The finally block is used for code that must always run, whether an error condition (exception) occurred or not.
The code in the finally block is run after the try block completes and, if a caught exception occurred, after the corresponding catch block completes. It should always run, even if an uncaught exception occurred in the try or catch block (Except if you got System.exit(0) in try block, because it will turn down the application before going to the finally block).
So your answer is 2. 30
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have to: create a code that demonstrates how various exceptions are caught: using the code template of:
catch (Exception exception)
Thanks for all of the helpful comments.
I've revised my code:
package exception;
import java.util.Scanner;
import java.io.*;
public class Exception
{
public static void main(String args[])
{
try
{
int a[] = new int[10];
System.out.println("Access element three :" + a[11]);
// The reason this is an exception is because there is no element 11 of the array. It only has 10.
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Exception thrown :" + e);
// This should print out whatever number was requested for a[e]
}
System.out.println("Out of the block");
// Once the exception is caught, this statement will be printed.
}
}
Output:
run:
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 11
Out of the block
BUILD SUCCESSFUL (total time: 1 second)
Now my question is: Is the format done correctly? The problem requires that I use
catch (Exception exception).
I'm not sure if that's what I did - If not how can I?
Once again, thanks everyone.
The problem is with the syntax of your try-catch block.
It should be as follows:
try {
//Here goes code that might throw an exception.
}
catch(Exception e)
{
//Here goes code to handle if an exception was thrown in the try block.
}
I'm assuming your assignment hander-outer wants you to not just throw and exception with "throw new java.lang.Exception();" But instead to write some code that might throw an exception.
If you want the code to work the way you're doing it, it'll look like this:
try {
java.lang.Exception exception = new java.lang.Exception();
throw exception;
}
catch(Exception e)
{
System.out.println("I caught one!, Here's it's info: ");
e.printStackTrace();
}
However, if you want to do it the correct way, it'll look something like this:
try {
int number = 500;
int result = number / 0;
//This will throw an exception for dividing by zero.
int[] array = new int[10];
int bad = array[11];
//This will throw an ArrayIndexOutOfBoundsException
}
catch(Exception e)
{
System.out.println("I caught one! Here's some info: ")
e.printStackTrace();
}
Of course, with the code above, as soon as the first exception is thrown (by dividing by zero), the catch block will catch it and break out of the try block, so the next bad piece of code isn't ever executed.
I recommend looking here for learning what you need to know for this assignment:
https://docs.oracle.com/javase/tutorial/essential/exceptions/try.html
Also here:
https://docs.oracle.com/javase/tutorial/essential/exceptions/handling.html
And here as well:
http://docs.oracle.com/javase/tutorial/essential/exceptions/
Good Luck!
EDIT
In your catch block, you can use "System.exit(1);" Which will stop your program and have it return 1, which means that it ended its execution with an error.
However, let's say you're wanting to get a user to enter their age. You can prompt them in a try block and in the case that they enter a negative number, you could catch it with an exception and prompt again until they enter a positive number. In that case, you wouldn't want to use System.exit(1) because then your program would stop when it could keep going, all because a user gave a bad input.
That isn't a good example because you shouldn't handle such trivial things, like negative numbers, with an exception. But the idea is the same. If you want your code to continue on, you'll want to handle the error and continue. The only time to use "System.exit(1);" is if your program can't fix the error given, or if your program only did one task and that task couldn't be completed with the given input or encounters an error in doing that task.
This has included some things the other answer forgot, like scriptability (it's a good thing!)
package exception;
//import java.util.Scanner; (unused import)
import java.lang.Exception;
public class ExceptionTester {
public static void main(String[] args) {
try {
throw new Exception("Error Message Here");
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
};
}
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Does a finally block always run?
let's imagine the following scenario:
public void myMethod() throws MyException
try
{
// do something
// an Exception (for example an individual written MyException which extends
// "Exception" is thrown here
}
catch (OtherException e)
{
// do something
}
finally
{
// do something else
}
}
In case "MyException" is thrown in the try block and would not be catched - they finally block would be reached nonetheless, correct?
What if it would be an Runtime Exception, which would be thrown? Would the finally block be reached?
Is there any case where a finally block won't be reached?
Thanks for an answer :-)
Finally is always called unless you have a vm crash or call System.exit.
In Java, what is the difference (in term of performance) between:
for (int i = 0; i < count; i++) {
try {
// code that throws Exception
} catch (Exception e) {
e.printStackTrace();
}
}
and
try {
for (int i = 0; i < count; i++) {
// code that throws Exception
}
} catch (Exception e) {
e.printStackTrace();
}
In your first version the loop continues if it hits an exception, in the second version the loop continues after the catch block. That is the most important difference of those code snippets.
You can use both, but it all depends on what you want it to do. If you want to continue the execution after the loop finishes once then you do it the first way. If you want to catch an exception then stop executing the loop then you do the second. Performance wise it all depends on what you want to do with it.
The main difference is that in the first snippet of code, even if there is an exception thrown from the try block and it is caught execution of the for loop continues. In the second snippet if an exception is thrown then the for loop is exited. This is because the whole loop is within the try block.
No I'm quite sure there's absolutely no difference from a point of performance here (ignoring the obvious fact about the loop). In both cases you create exactly one entry in the exception table - only the PC values (ie in which range the exception is valid) will be a bit different.
ie if you assume the following is the exception table the only thing that'll change are the x, y and z values..
Exception table:
from to target type
x y z <Class java.lang.Exception>
Since you asked about performance in the two versions of code, I am reminded of "Practical Java" (Addison-Wesley 2000) which recommends in Praxis 23: Place try/catch blocks outside of loops. The reason involves running the code on a JVM with the JIT compiler turned off. In that case, the lack of run-time JIT optimizations results in extra branches in the opcode, leading to reduced performance. You can read JIT docs of 2014 here: http://www.oracle.com/technetwork/articles/java/architect-evans-pt1-2266278.html
Besides the difference in your logic with the continuing for. It's no noticeable difference between
try {
lots of stuff which might not throw any exception
something that throws exception
} catch (Exception e) {
}
and
lots of stuff which might not throw any exception
try {
something that throws exception
} catch (Exception e) {
}