Exception Handling Unreachable code - java

Following is my code, when I am commenting statement-2 then it complies fines but when I uncomment it gives Compile Time Error "Unreachable Code".
I understand why I am getting error after uncommenting it, but my question is even if I comment it still the bad() is unreachable as I am throwing an exception is catch then why it is not giving error for it ?
class Varr
{
public static void main(String[] args) throws Exception
{
System.out.println("Main");
try {
good();
} catch (Exception e) {
System.out.println("Main catch");
//**Statement 1**
throw new RuntimeException("RE");
} finally {
System.out.println("Main Finally");
// **Statement 2**
throw new RuntimeException("RE2");
}
bad();
}
}

but my question is even if i comment it still the bad() is
unreachable as i am throwing an exception is catch then why it is not
giving error for it ?
Because the execution will not necessary enter in the catch statement.
Suppose that good() doesn't thrown any exception, so you don't enter in the catch and therefore bad() is then executed :
public static void main(String[] args) throws Exception
{
System.out.println("Main");
try {
good(); // doesn't throw an exception
} catch (Exception e) {
System.out.println("Main catch");
throw new RuntimeException("RE");
}
bad(); // execution goes from good() to here
}

Related

finding error in throw Exception

i received this error from my code and can't seem to find a solution. This is my first time handling throw exception in java. Any help is appreciated!
C:\Users\acer\Documents\MyFinal3.java:5: error: ';' expected
static void exceptionFinal() throw RuntimeException();{
1 error
import java.io.*;
import java.util.*;
public class MyFinal3
{
static void exceptionFinal() throw RuntimeException eE{
System.out.println("Inside exceptionFinal");
throw RuntimeException();
}
public static void main(String []args)
{
double myDouble[] = new double[5];
try {
exceptionFinal();
System.out.println("Access element sixth :" +
myDouble[6]);
}
catch (RuntimeException eE) {
System.out.println("Exception thrown: 1");
}
catch (Exception eE) {
System.out.println("Exception thrown: 2");
}
catch (ArrayIndexOutOfBoundsException eE) {
System.out.println("Exception thrown: 3" );
}
finally {
System.out.println("Exception end" );
}
System.out.println("Out of the block");
}
}
your code has multiple issues and surely shows the lack of basic understanding of java, but in order to compile your current code, you should rewrite it as follows. Note the differences in the usage of throw and throws. As one of the comment suggested, please review Difference between throw and throws in Java?
import java.io.*;
import java.util.*;
public class MyFinal3 {
static void exceptionFinal() throws RuntimeException {
System.out.println("Inside exceptionFinal");
throw new RuntimeException();
}
public static void main(String[] args) {
double myDouble[] = new double[5];
try {
exceptionFinal();
System.out.println("Access element sixth :" + myDouble[6]);
} catch (RuntimeException eE) {
System.out.println("Exception thrown: 1");
} catch (Exception eE) {
System.out.println("Exception thrown: 2");
}
finally {
System.out.println("Exception end");
}
System.out.println("Out of the block");
}
}
As moonlighter suggested, the problem lies in the "throw"-keyword. The "throw" tell's java to throw an exception right away, which cannot be done in the method-signature (hence the syntax error). On the other hand, the "throws" marks a method that might be throwing an exception.
Another nice thing is to indent your code. This improves the readability both for you and people that might help you.

Getting compilation error in main even though try catch finally block is added in the calling method

I am trying to run the below code but getting compilaton error as "Unhandled exception type FileNotFoundException", as per my understanding this should not happen since try catch and finally blocks are added in the calling method.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class Test
{
public static void main(String[] args)
{
myMethod();
}
public static void myMethod() throws FileNotFoundException
{
try
{
System.out.println("In the try block");
FileInputStream fis = new FileInputStream("file.txt");
}
catch(Exception e)
{
System.out.println("in the catch block");
throw e;
}
finally
{
System.out.println("in the finally block");
}
}
}
Remove throws FileNotFoundException from the myMethod signature (and then you'll need to remove throw e; from the catch block).
Or, add a try and catch to your main method (to handle the FileNotFoundException that you have indicated myMethod can throw).
Or, add throws FileNotFoundException to the signature of main (as pointed out by Andreas in the comments).
In short, the compiler will not allow you to have a code path with checked exceptions that are not handled.
In the catch block, you are throwing the Exception again once you catch it. If you really want to throw it from the myMethod() even after catch it, just add another try-catch to the main method.
public static void main(String[] args){
try{
myMethod();
}catch(FileNotFoundException e){
System.out.println("catch block in main");
}
}
Or else if you want to just catch the Exception in your myMethod(), don't throw it back.
try{
System.out.println("In the try block");
FileInputStream fis = new FileInputStream("file.txt");
}
catch(Exception e){
System.out.println("in the catch block");
}
finally{
System.out.println("in the finally block");
}
you can read more about re-throwing exceptions in following question.
Rethrow exception in java

How does exception chain work in my code?

Why this code doesn't print "d". Why it doesn't go to the catch block for RunTimeException?
public static void main(String[] args) {
System.out.println("a");
try {
System.out.println("b");
throw new IllegalArgumentException();
} catch (IllegalArgumentException e) {
System.out.println("c");
throw new RuntimeException();
}catch (RuntimeException e) {
System.out.println("d");
throw new RuntimeException();
}finally{
System.out.println("e");
throw new RuntimeException();
}
}
The output of this program is
a
b
c
e
Exception in thread "main" java.lang.RuntimeException
EDIT: After throwing IllegalArgumentException it goes to the corresponding catch block and prints 'c'. after that since we don't catch the exception in RuntimeException it doesn't go any further. but since it's guranteed that we go to the finally block it print 'e' and after that throw RunttimeException. if the code was like something like the following, it would throw out the RuntimeException("2"). If we comment the exception inside finally, it throw out RuntimeException("1").
public static void main(String[] args) throws InterruptedException {
System.out.println("a");
try {
System.out.println("b");
throw new IllegalArgumentException();
} catch (IllegalArgumentException e) {
System.out.println("c");
throw new RuntimeException("1");
}catch (RuntimeException e) {
System.out.println("d");
throw new RuntimeException();
}finally{
System.out.println("e");
throw new RuntimeException("2");
}
}
The reason of this code not printing d is, because in the IllegalArgumentException catch block, after printing "c" and before throwing RuntimeException it executes finally (that's how the flow works). Finally block throws exception itself, so It never gets to throw that RuntimeException that gets it to "d".
public static void main(String[] args) {
System.out.println("a");
try {
System.out.println("b"); // 1
throw new IllegalArgumentException(); // 2
} catch (IllegalArgumentException e) {
System.out.println("c"); // 3
throw new RuntimeException(); // nope, there's a finally block that executes first
}catch (RuntimeException e) {
System.out.println("d");
throw new RuntimeException();
}finally{
System.out.println("e"); // 4
throw new RuntimeException(); // 5 - rest of the code never got executed.
}
}
Hope this was clear enough.
Also, as it was pointed out, even if the RuntimeException after "c" was executed, It would not invoke the lower catch block. The catch block is only invoked once, depending on the Exception thrown in the try block (though this isn't really relevant because the first explanation dictates the flow of your thread).
The catch blocks are NOT in the scope of the try. Any code in the catch blocks executes in the context of the outer main code, and thus has no exception handlers. When you throw RuntimeException the finally block for the try gets executed and then the exception terminates the program.
In try catch block, if one of the catch block catches the exception the other catches doesn't get involved. remeber that finally block always run at the end no matter exception gets threw or not.

Is "precise rethrow with a final exception" working in Java SE 8?

public class TestException extends except2 {
public static void main(String[] args)throws Exception {
try {
try {
throw new TestException();
}
catch (final TestException e){
}
throw new except2();
}
catch (TestException a){
}
catch (Exception e){
throw e;
}
}
public TestException(){
}
}
class except2 extends Exception{
}
Hi all,
my JDK version is 8u45 which is latest one now.
I'm wondering that is "precise rethrow with a final exception" still working in SE 8?
As the code, if I take the "throws Exception" off it'll be compilation error, but it should be able to be ignored according to "precise rethrow with a final exception" function of SE7.
Another question is that we all know if there's an exception happened in the nested try box, we should still throw it out to outer catch box to avoid compilation error, I originally figured that we only need to throw an exception of any types & it'll do, so is my test result, I think it's to let compiler know that there's an exception in try box & catch box got it, too.
but if I alter it like the following code:
public class TestException extends except2 {
public static void main(String[] args)throws Exception {
try {
try {
throw new ArithmeticException();
} catch (final TestException e){
throw e;
}
} catch (TestException a){
} catch (Exception e){
throw e;
}
}
}
the (final TestException e) part will be compilation error with the message:
"the Exception "com.xxx.TestException" is never thrown in the corresponding try block",
and I'm confused because if nested catch block can't handle the exception, it shall goes to outer.
Then if I throw an ArithmeticException in the end of outer try block like this:
try {
try {
throw new TestException();
}
catch (final TestException e){
System.out.println("d");
}
throw new ArithmeticException();
}
catch (TestException a){
}
catch (Exception e){
throw e;
}
Same error to the outer catch box catch (TestException a){}
Why is that?
it should be caught by (Exception e) block.
If I can't throw different types of exception from the first exception of nested try block, why could I throw except2 in the first paragraph of code?
This is Oracles example for the feature, and it still works with Java 8:
static class FirstException extends Exception { }
static class SecondException extends Exception { }
public void rethrowException(String exceptionName)
throws FirstExceptio, SecondException // Since J7 no "Exception" needed
{
try {
if (exceptionName.equals("First")) {
throw new FirstException();
} else {
throw new SecondException();
}
} catch (Exception e) {
throw e; // effective final (i.e. not assigned)
}
}
This is described in the second half of this Oracle document. Your examples are all not really related to it. Especially not the one where you have a more specific and a general catch. This is explicitly mentioned in the document as not working.
Your first block would work if you use except2 (I renamed it to BaseException) which is the more specific one like this:
public class TestException extends BaseException {
public static void main(String[] args) {
try {
try {
throw new TestException();
}
catch (final BaseException e){
throw e; // this is defined as BaseEx, will fail on Java 6
}
}
catch (TestException a){ // this knows that no BaseEx is expected
}
}
public TestException(){
}
}
class BaseException extends Exception { }
As you can see, the main() method does not need to throw Exception anymore since the second catch block was sufficient.
Your first piece of code can be shortened to
class TestException extends except2 throws Exception {
public static void main(String[] args) {
try {
throw new except2(); // this
} catch (TestException a) {
} catch (Exception e) {
throw e;
}
}
public TestException() {
}
}
class except2 extends Exception {
}
You're throwing an except2. A TestException is an except2, but an except2 is not necessarily a TestException. The first catch block cannot handle the except2 exception. So the second one must. Since it further throws that exception, and that exception is necessarily checked, you need to have a throws clause.
Your second piece of code
class TestException extends except2 {
public static void main(String[] args) throws Exception {
try {
try {
throw new ArithmeticException();
} catch (final TestException e) { // nothing above throws a TestException
throw e;
}
} catch (TestException a) {
}
catch (Exception e) {
throw e;
}
}
}
Is trying to catch a TestException in the nested try block. But since TestException is a checked exception, the compiler can and does check if it can be thrown in that block. In your case, it can't. So it complains that's it useless to try and catch it.
Finally, in your last snippet
class TestException extends except2 {
public static void main(String[] args) throws Exception {
try {
try {
throw new TestException();
} catch (final TestException e) {
System.out.println("d");
}
throw new ArithmeticException();
} catch (TestException a) {
} catch (Exception e) {
throw e;
}
}
}
You're throwing and catching a TestException in the nested try-catch statement. So you can reduce the code to
class TestException extends except2 {
public static void main(String[] args) throws Exception {
try {
throw new ArithmeticException();
} catch (TestException a) {
} catch (Exception e) {
throw e;
}
}
}
Which has the same issue as your second piece of code. There is no code path there that can throw a TestException.
Regarding comments, and to simplify the second snippet, the error reduces to
class TestException extends except2 {
public static void main(String[] args) throws Exception {
try {
throw new ArithmeticException();
} catch (final TestException e) { // nothing above throws a TestException
throw e;
}
}
}
You have a catch(TestException) but nothing throws a TestException, so it's useless code which the compiler rejects.
From comments, this is the problem with your cases 2 and 3
// ignore everything around this
try {
// nothing in this block
// can throw a TestException
throw new ArithmeticException();
// this whole catch block is useless code
// Test Exception can never be thrown
} catch (final TestException e){
throw e;
}
// ignore everything around this

catch multiple exceptions at once in java?

import java.io.*;
class West1 extends Exception {
private String msg;
public West1() {
}
public West1(String msg) {
super(msg);
this.msg=msg;
}
public West1(Throwable cause) {
super(cause);
}
public West1(String msg,Throwable cause) {
super(msg,cause);
this.msg=msg;
}
public String toString() {
return msg;
}
public String getMessage() {
return msg;
}
}
public class West {
public static void main(String[] args) {
try {
throw new West1("Custom Exception.....");
}catch(West1 ce) {
System.out.println(ce.getMessage());
//throw new NumberFormatException();
throw new FileNotFoundException();
}catch(FileNotFoundException fne) {
fne.printStackTrace();
}/*catch(NumberFormatException nfe) {
nfe.printStackTrace();
}*/
}
}
In the above code, NumberFormatException is thrown from catch block it compile and run successfully but when FileNotFoundException is thrown from catch block it will not compile. Following Errors are thrown:
West.java:40: error: exception FileNotFoundException is never thrown in body of
corresponding try statement
}catch(FileNotFoundException fne){
West.java:39: error: unreported exception FileNotFoundException; must be caught
or declared to be thrown
throw new FileNotFoundException();
So my question is what is reason behind this behaviour?
NumberFormatException is a RuntimeException, meaning that it's not required to be declared in all methods it may be thrown. This means that, unlike FileNotFoundException, the compiler can not know if it can get thrown in a block or not.
The title implies you are trying to catch multiple exceptions at once, and your code implies you understand that you can have multiple catch blocks for a single try block to catch different types of exceptions. Everything is good so far, but you seem to misunderstand exactly where the try-catch catches errors.
Here is you code. I removed the comments to make it more concise.
public class West {
public static void main(String[] args) {
try {
throw new West1("Custom Exception.....");
} catch(West1 ce) {
System.out.println(ce.getMessage());
throw new FileNotFoundException(); // <-- Must be caught
} catch(FileNotFoundException fne) { // <-- Never thrown
fne.printStackTrace();
}
}
}
The first compiler error is because the catch block that is for catching FileNotFoundException's try block never throws FileNotFoundException. The second compiler error is because FileNotFoundException is a checked exception. Because it is a checked exception your code must either
handle it (by catching it with try-catch)
let everyone know it could throw it (public static void main(String[] args) throws FileNotFoundException { ...).
From the context of your code, you seem to be going with the first option, handling it with try-catch, but you have the catch in the wrong place.
catch blocks don't catch exceptions, try blocks do. catch blocks specify what to do with the actual caught exception.
public class West {
public static void main(String[] args) {
try {
throw new West1("Custom Exception.....");
} catch(West1 ce) {
System.out.println(ce.getMessage());
try {
throw new FileNotFoundException();
} catch(FileNotFoundException fne) {
fne.printStackTrace();
}
}
}
}
Try that instead. Notice how you can have a try instead of a catch. This wouldn't matter if FileNotFoundException wasn't a checked exception.

Categories

Resources