finding error in throw Exception - java

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.

Related

Exception Handling Unreachable code

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
}

Throw, Catch exception mistakes

Im confused how throw and catch work,I understand their are several mistakes with this ExceptionDemo. If someone could fix the mistake and clearly state why and how they corrected it without using all the Java jargon words, and use simple terms
Thank you
public class ExceptionDemo {
public static void main( String [] args ) {
try {
int number = Integer.parseInt(”123”);
if (number > 100) {
catch new ArithmeticException(”Check the number”);
}
}
catch {
System.out.println(”Cannot convert to int”);
}
finally (Exception e) {
System.out.println(”Always print”);
}
}
}
a bit tricky to tell exactly what is needed here. for starters looks like as would need to throw an exception if checking for some sort of valid value. also looks like the catch would need to have the exception handler itself not the finally.
//listing 1 slight re-work original post
public class Main {
public static void main(String[] args) throws ArithmeticException {
try {
int number = Integer.parseInt("123");
if (number > 100) {
// is this what trying to do?
//would expect typically would be used to handle
//something like div by zero, etc.
throw new ArithmeticException("Check the number");
}
}
//catch exception(s) here
catch (Exception e) {
System.out.println("Cannot convert to int:" + e.toString());
}
finally {
System.out.println("Always print");
}
}
}
//listing 2 more typical type thing maybe
public class Main {
public static void main(String[] args) {
try {
//int number = Integer.parseInt("A123"); // if un-comment throws generic exception bad input
int number = 100 / 0; //will throw an "arithmetic" exception
//
if (number > 100) {
//do something.
int x = number++;
}
}
catch (ArithmeticException arithEx){
System.out.println("An ArithmeticException Occurred:" + arithEx.toString());
}
catch (Exception e) {
System.out.println("A general exception occurred:" + e.toString());
}
finally {
//always gets executed. so is good place to clean up, close connections etc.
System.out.println("Always print");
}
}
}
In addition to hurricane's answer, you cannot catch a new exception. Instead you need to throw it.
throw new Exception();

Catch handler for multiple exceptions?

I am experimenting with exceptions and i want to ask when it is possible to handle multiple exceptions in one handler and when it is not?
For example i wrote the following code which combines two exceptions (FileNotFoundException OutOfMemoryError) and the program runs properly without any error. Al thought the handling is not so relevant with the functionality of the code i chose them just to see when i can combine multiple exceptions in on handler :
import java.io.FileNotFoundException;
import java.lang.OutOfMemoryError;
public class exceptionTest {
public static void main(String[] args) throws Exception {
int help = 5;
try {
foo(help);
} catch (FileNotFoundException | OutOfMemoryError e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static boolean foo(int var) throws Exception {
if (var > 6)
throw new Exception("You variable bigger than 6");
else
return true;
}
}
But when i choose different type of exceptions the compiler gives me error . For example when i choose IOException and Exception i have the error the exception is already handled " :
import java.io.IOException;
import java.lang.Exception;
public class exceptionTest {
public static void main(String[] args) throws Exception {
int help = 5;
try {
foo(help);
} catch (IOException | Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static boolean foo(int var) throws Exception {
if (var > 6)
throw new Exception("You variable bigger than 6");
else
return true;
}
}
So why is this happening ? Why in one occasion i can use multiple exception in handler and in the other not ? Thank you in advance.
You are getting the message because IOException is a subclass of Exception. Therefore, if an IOException were thrown, it would be caught by a catch (Exception e) statement, so catching it as an IOException is redundant.
The first example works because neither FileNotFoundException nor OutOfMemoryError is a subclass the other.
However, you can catch sub-classed exceptions using the separate catch statement:
try{
// code that might throw IOException or another Exception
} catch (IOException e) {
// code here will execute if an IOException is thrown
} catch (Exception e) {
// code here will execute with an Exception that is not an IOException
}
If you do this, please note that the subclass must come first.

IOException can not be resolved to a type error

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 .

exception.getMessage() output with class name

I'm trying to fix an issue, in my application I have this code
try {
object1.method1();
} catch(Exception ex) {
JOptionPane.showMessageDialog(nulll, "Error: "+ex.getMessage());
}
and the object1 would do something like that:
public void method1() {
//some code...
throw new RuntimeException("Cannot move file");
}
I get a messsage in my option pane like this:
Error: java.lang.RuntimeException: Cannot move file
but I used getMessage and not toString method, so the name of the class shouldn´t appear, right?
What I am doing wrong?
I already tryied with a lot of exceptions, even Exception itself. I'm looking to solve this no without the need to implement my own Exception subclass
PROBLEM SOLVED - thank you all!
The try and catch were actually being called in get() method from SwingWorker which constructs an ExecutionException with my exception thrown from doInBackground()
I fixed doing this:
#Override
protected void done() {
try {
Object u = (Object) get();
//do whatever u want
} catch(ExecutionException ex) {
JOptionPane.showMessageDialog(null, "Error: "+ex.getCause().getMessage());
} catch(Exception ex) {
JOptionPane.showMessageDialog(null, "Error: "+ex.getMessage());
}
}
I think you are wrapping your exception in another exception (which isn't in your code above). If you try out this code:
public static void main(String[] args) {
try {
throw new RuntimeException("Cannot move file");
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage());
}
}
...you will see a popup that says exactly what you want.
However, to solve your problem (the wrapped exception) you need get to the "root" exception with the "correct" message. To do this you need to create a own recursive method getRootCause:
public static void main(String[] args) {
try {
throw new Exception(new RuntimeException("Cannot move file"));
} catch (Exception ex) {
JOptionPane.showMessageDialog(null,
"Error: " + getRootCause(ex).getMessage());
}
}
public static Throwable getRootCause(Throwable throwable) {
if (throwable.getCause() != null)
return getRootCause(throwable.getCause());
return throwable;
}
Note: Unwrapping exceptions like this however, sort of breaks the abstractions. I encourage you to find out why the exception is wrapped and ask yourself if it makes sense.
My guess is that you've got something in method1 which wraps one exception in another, and uses the toString() of the nested exception as the message of the wrapper. I suggest you take a copy of your project, and remove as much as you can while keeping the problem, until you've got a short but complete program which demonstrates it - at which point either it'll be clear what's going on, or we'll be in a better position to help fix it.
Here's a short but complete program which demonstrates RuntimeException.getMessage() behaving correctly:
public class Test {
public static void main(String[] args) {
try {
failingMethod();
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
private static void failingMethod() {
throw new RuntimeException("Just the message");
}
}
Output:
Error: Just the message

Categories

Resources