-1

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");
}
}
mehulmpt
  • 15,861
  • 12
  • 48
  • 88
echaju
  • 11
  • 5

2 Answers2

0

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");
  }
}
moonlighter
  • 541
  • 3
  • 14
  • thank you! yes i will learn more in the future i just can't seem to wrap my head on throw exception since it confuses me a lot..but regardless thanks! – echaju Jan 02 '18 at 20:48
0

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.

retler
  • 3
  • 3