"misplaced construct(s)" in Java code near a catch - java

I could not compile the following code in Java, error is: misplaced construct(s). What's wrong?
public class ExceptionsTutorial {
public static void main(String[] argv) throws Exception{
try{
System.out.println("A");
try{
System.out.println("B");
throw new Exception("1");
}
catch{
System.out.println("C");
throw new Exception("2");
}
finally{
System.out.println("D");
throw new Exception("3");
}
}
finally{
System.out.println("F");
}
}
}

catch must declare what exception it catches:
catch (Exception E) {
System.out.println("C");
throw new Exception("2");
}

Read up on Java catch blocks. There is a required element that is missing in your code.
Note that Java's behavior is slightly different from that of C# or Python in this regard.

Related

Add 2 exception in java [duplicate]

For my final in Java we have a "exceptions" part on the test with try, catch, and finally calls. When I try to put the example code into Eclipse I get errors in the catch and throw new areas. All of the errors say "Can not be resolved to type".
How do I fix this so I can learn/review what the code is supposed to be doing?
Q4 Class
public static void main(String [] args)
{
Q4Exception q1 = new Q4Exception();
try{
q1.sampleMethod();
try{
q1.sampleMethod();
}
//This catch does not throw an error
catch(RuntimeException es)
{
System.out.println("A");
}
//This catch below throws the error of cannot be resolved to a type
catch(IOException es)
{
System.out.println("B");
}
//This catch does not throw an error
catch(Exception e)
{
System.out.println("C");
}
finally{
System.out.println("D");
}
}catch(Exception e)
{
System.out.println("E");
}
finally{
System.out.println("F");
}
}
Q4Exception Class
public void sampleMethod() throws Exception
{
try{
throw new IOException("H");
}
catch(IOException err)
{
System.out.println("I");
throw new RuntimeException("J");
}
catch(Exception e)
{
System.out.println(e.toString());
System.out.println("K");
throw new Exception(“L");
}
catch(Throwable t)
{
System.out.println("M");
}
finally{
System.out.println("N");
}
}
I think it's worth mentioning that in Eclipse, Ctrl+Shif+O does the job of resolving the imports for you.
Oh, guess I could answer my own question here.
Didn't know I had to import the IOException from java.io!
Easy to just use
import java.io.*
for the imports
I discovered I was using an old version of JWT , the issue is gone after using the a newer version of JWT dependency .

Java Custom Exceptions

I want to reproduce a part of InterruptedException behavior but I don't understand how it works...
So I have this code:
public static void main(String [] args){
try{
}catch(InterruptedException ie){
}
}
When I try to compile it I get this compiler error
Unreachable catch block for InterruptedException. This exception is never thrown from the try statement body
I made a custom Exception which is not really an Exception because it doesn't extend Exception...
class MyException extends Throwable{
}
public static void main(String [] args){
try{
}catch(MyException ie){
}
}
Which shows the same compiler error
Unreachable catch block for MyException. This exception is never thrown from the try statement body
Then I did this
public static void main(String [] args){
try{
throw new MyException();
} catch(MyException e){
e.printStackTrace();
}
try{
throw new InterruptedException();
} catch(InterruptedException e){
e.printStackTrace();
}
}
And both of them compile fine.
But now comes the tricky part..
public static void main(String [] args){
try{
throw new MyException();
} catch(Exception e){
e.printStackTrace();
} catch(MyException e){
e.printStackTrace();
}
try{
throw new InterruptedException();
} catch(Exception e){
e.printStackTrace();
} catch(InterruptedException e){
e.printStackTrace();
}
}
Compiler says
Unreachable catch block for InterruptedException. It is already handled by the catch block for Exception
Can you tell me how InterruptedException shows the "Unreachable catch block for InterruptedException. This exception is never thrown from the try statement body" compiler error and extends Exception in the same time, because when I extend exception my custom exceptions don't show this compiler error
As an example:
class MyException extends Exception{}
public static void main(String [] args){
try{
}catch(MyException me){
}
}
This code doesn't throw any compiler error
But the following code does
class MyException extends Throwable{}
public static void main(String [] args){
try{
}catch(MyException me){
}
}
This occurs because InterrupedException is a subclass of Exception, but Exception is already caught by the preceding catch block.
Section 11.2.3 of the JLS states:
It is a compile-time error if a catch clause can catch an exception class E1 and a preceding catch clause of the immediately enclosing try statement can catch E1 or a superclass of E1.
The block in the InterruptedException catch block would be unreachable code, which would be the justification for this compiler error.
You are chatching throwable exception so it has to be thrown from somewhere
by the way : my compiler shows error for 1st script and for 2nd script

Why it is okay in java 7 to catch an IOException even if IOException will never be thrown

public class SampleCloseable implements AutoCloseable {
private String name;
public SampleCloseable(String name){
this.name = name;
}
#Override
public void close() throws Exception {
System.out.println("closing: " + this.name);
}
}
and the main class
public class Main{
public static void main(String args[]) {
try(SampleCloseable sampleCloseable = new SampleCloseable("test1")){
System.out.println("im in a try block");
} catch (IOException e) {
System.out.println("IOException is never thrown");
} catch (Exception e) {
} finally{
System.out.println("finally");
}
}
}
But when i removed the throws exception on close() method inside SampleCloseable
i am getting a compiler error saying that IOException is never thrown in the corresponding try block.
Because you're throwing a generic Exception. Since an IOException inherits from Exception, it might be thrown by the close() method. The caller doesn't know that it doesn't actually get thrown. It only sees the method signature that says that it could.
In fact, the close() method is free to throw any Exception of any kind. Of course that's bad practice, you should specify what specific Exceptions you're throwing.
Your confusion may that around the fact the in Java 7, the exception that is [declared to be] thrown from the close method is thrown inside the try block, so your catch block has to catch it as well.
Your close method is declared to throw an Exception, so your catch blocks have to catch that, or the method has to be declared to throw Exception.
And since IOException is a subclass of Exception, you are of course allowed to try and catch that as well, as long as your also catch/declare Exception itself.
See JLS 14.20.3.2:
The meaning of an extended try-with-resources statement [...] is given
by the following translation to a basic try-with-resources statement
(§14.20.3.1) nested inside a try-catch or try-finally or
try-catch-finally statement.
Your code is effectively translated to the below. Although a bit longish, it should be clear from the below what's happening in your code.
public static void main(String args[]) {
try {
Throwable primaryEx = null ;
SampleCloseable sampleCloseable = new SampleCloseable("test1")
try {
System.out.println("im in a try block");
} catch (Throwable t) {
primaryEx = t;
throw t;
} finally {
if (sampleCloseable != null) {
if (primaryEx != null) {
try {
sampleCloseable.close();
} catch (Throwable suppressedExc) {
primaryEx.addSuppressed(suppressedExc);
}
} else {
sampleCloseable.close();
}
}
} catch (IOException e) {
System.out.println("IOException is never thrown");
} catch (Exception e) {
} finally{
System.out.println("finally");
}
}

how to throw an IOException?

public class ThrowException {
public static void main(String[] args) {
try {
foo();
}
catch(Exception e) {
if (e instanceof IOException) {
System.out.println("Completed!");
}
}
}
static void foo() {
// what should I write here to get an exception?
}
}
Hi! I just started learning exceptions and need to catch an expetion, so please can anybody provide me with a solution?
I'd be very grateful.
Thanks!
static void foo() throws IOException {
throw new IOException("your message");
}
try {
throw new IOException();
} catch(IOException e) {
System.out.println("Completed!");
}
I just started learning exceptions and need to catch an exception
To throw an exception
throw new IOException("Something happened")
To catch this exception is better not use Exception because is to much generic, instead, catch the specific exception that you know how to handle:
try {
//code that can generate exception...
}catch( IOException io ) {
// I know how to handle this...
}
If the goal is to throw the exception from the foo() method, you need to declare it as follows:
public void foo() throws IOException{
//do stuff
throw new IOException("message");
}
Then in your main:
public static void main(String[] args){
try{
foo();
} catch (IOException e){
System.out.println("Completed!");
}
}
Note that, unless foo is declared to throw an IOException, attempting to catch one will result in a compiler error. Coding it using a catch (Exception e) and an instanceof will prevent the compiler error, but is unnecessary.
throw new IOException("Test");
Please try the following code:
throw new IOException("Message");
Maybe this helps...
Note the cleaner way to catch exceptions in the example below - you don't need the e instanceof IOException.
public static void foo() throws IOException {
// some code here, when something goes wrong, you might do:
throw new IOException("error message");
}
public static void main(String[] args) {
try {
foo();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}

In Java, if a general exception is caught and rethrown, will outer methods still be able to catch specific exceptions?

In Java, if a general exception is caught and rethrown, will outer methods still be able to catch specific exceptions?
In other words, can I do this:
try {
try {
//...
} catch (Exception e) {
//...
throw e;
}
} catch (SpecificException e) {
//...
}
re-throwing an exception does not change anything about it (it's still the same object originally thrown).
While jtahlborn answer is correct, there is one more appreciation: the compiler will see that you are throwing an exception of the generic type (even if at runtime it can be only of the specific class) and will force you to declare the generic exception in the method header.
private void test() throws FileNotFoundException {
try {
throw new FileNotFoundException("Es una exception");
} catch (IOException e) {
throw e; <-- Error because the method only throws
FileNotFoundException, not IOException
}
}
e is indeed FileNotFoundException, but as it is declared as IOException the compiler works with the broader class. What you can do is "cast" the exception.
throw (FileNotFoundException) e;
Eclipse marks the "throw e" in the inner catch as an unhandled exception, BUT it does catch the exception because when I run this it prints "It worked!". Thanks #jtahlborn. Unfortunately this means that there will still need to be an unnecessary try/catch block somewhere.
public class Tester {
public static void main(String[] args) {
try {
try {
throw new SpecificException("Test!");
} catch (Exception e) {
throw e;
}
} catch (SpecificException e) {
System.out.println("It worked!");
}
}
}

Categories