1

Also, what does throws NumberFormatException, IOException mean? I keep trying to use BufferedReader by saying

BufferedReader nerd = new BufferedReader(new InputStreamReader(System.in));

but BufferedReader won't work unless throws NumberFormatException, IOException is put in.

Vikdor
  • 23,934
  • 10
  • 61
  • 84
fifteenthfret
  • 83
  • 1
  • 1
  • 4
  • Did you check the documentation? – SLaks Sep 21 '12 at 02:58
  • 2
    http://docs.oracle.com/javase/tutorial/essential/exceptions/throwing.html – Sean F Sep 21 '12 at 02:59
  • ever thought of puuting the code in try catch and there catching these exceptions one by one [ if jdk <=1.6] , or at the same time [ if jdk =1.7] – Satya Sep 21 '12 at 03:00
  • Did you consider reading the manual first?? Here you go : http://docs.oracle.com/javase/tutorial/getStarted/TOC.html – Alex Calugarescu Sep 21 '12 at 03:39
  • possible duplicate of [What's the purpose of the 'throws' statement in Java?](http://stackoverflow.com/questions/6553940/whats-the-purpose-of-the-throws-statement-in-java) – ctacke Sep 21 '12 at 15:19
  • Related question with useful answers: [Why is “throws Exception” necessary when calling a function?](https://stackoverflow.com/q/11589302/86967) – Brent Bradburn Apr 12 '18 at 20:59

3 Answers3

5

The throws keyword indicates that a certain method can potentially "throw" a certain exception. You need to handle a possible IOException (and possibly other exceptions) either with a try-catch block or by adding throws IOException, (...) to your method declaration. Something like this:

public void foo() throws IOException /* , AnotherException, ... */ {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    in.readLine();
    // etc.
    in.close();
}


public void foo() {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    try {
        in.readLine();
        // etc.
        in.close();
    } catch (IOException e) {
        // handle the exception 
    } /* catch (AnotherException e1) {...} ... */
}
arshajii
  • 127,459
  • 24
  • 238
  • 287
4

Throws clause is used to declare the exceptions that are not handled by a particular method and is an instruction to the callers to either handle these explicitly or rethrow them up in the call hierarchy.

Vikdor
  • 23,934
  • 10
  • 61
  • 84
1

The throws statement means that the function, may 'throw' an error. Ie spit out an error that will end the current method, and make the next 'try catch' block on the stack handle it.

In this case you can either add 'throws....' to the method declaration or you can do:

try {
    // code here
} catch (Exception ex) {
    // what to do on error here
}

Read http://docs.oracle.com/javase/tutorial/essential/exceptions/ for more info.

md_5
  • 630
  • 9
  • 26