LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Java "throws IOException" problem (https://www.linuxquestions.org/questions/programming-9/java-throws-ioexception-problem-140509/)

Nylex 01-30-2004 04:59 PM

Java "throws IOException" problem
 
Lo all, can someone tell me what's wrong with this code please:

Code:

import java.io*;

public class test throws IOException
{
    public static void main(String[] args)
    {
          BufferedReader reader = new BufferedReader(new InputStreamReader(System.in);

          System.out.print("Enter your name: ");
          String name = reader.readLine();
    }
}

NetBeans IDE won't let me compile and keeps saying '{ expected'. Where?! I don't think I've missed one :/.

wapcaplet 01-30-2004 05:32 PM

I'm not too knowledgable about Java, but I don't think a class can throw an exception; only functions can throw exceptions. Try:

Code:

public class test
{
  public static void main(String[] args) throws IOException
    {
      ...
    }
}


Nylex 01-30-2004 05:39 PM

Yep, you're right. Thanx a lot.

coolman0stress 01-30-2004 05:39 PM

wapcaplet is correct, classes are not declared to throw exceptions

eric.r.turner 01-30-2004 08:37 PM

Re: Java "throws IOException" problem
 
Quote:

Originally posted by Nylex
Code:

          BufferedReader reader = new BufferedReader(new InputStreamReader(System.in);
NetBeans IDE won't let me compile and keeps saying '{ expected'. Where?! I don't think I've missed one :/.

Though the previous post is true about exceptions only being thrown by methods, that isn't what the compiler error you gave us was referring to. The problem is that you missed the last parenthesis! It should be:

Code:

          BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
The reason it is complaining about expecting a '{' is that the compiler thinks you're trying to define an anonymous inner class. For example, look at this code carefully:

Code:


JFrame frame = new JFrame();

frame.addWindowListener( new WindowAdapter() {
  public void windowClosing( WindowEvent event ) {
      System.exit( 0 );
  }
});

Notice the '{' immediately after 'WindowAdapter()'. That's what the compiler was expecting. This type of code is what you often see for exiting an application when a window closes. What we're doing here is defining and instantiating a class that inherits from WindowAdapter, overriding WindowAdapter's windowClosing method. All of this is done as an argument to the addWindowListener method! It's a strange syntax.

wapcaplet 01-30-2004 08:49 PM

Ah yes, good point.

In times like these, it's good to have an editor that gives you a lot of visual clues that a parenthesis or bracket is not closed. Vim for example :)


All times are GMT -5. The time now is 07:47 AM.