Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get the "Unhandled exception type IOException"?

I have the following simple code:

import java.io.*; class IO {     public static void main(String[] args) {            BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));            String userInput;            while ((userInput = stdIn.readLine()) != null) {           System.out.println(userInput);        }     } } 

And I get the following error message:

---------- 1. ERROR in io.java (at line 10)     while ((userInput = stdIn.readLine()) != null) {                         ^^^^^^^^^^^^^^^^ Unhandled exception type IOException ---------- 1 problem (1 error)roman@roman-laptop:~/work/java$ mcedit io.java  

Does anybody have any ideas why? I just tried to simplify the code given on the sum web site (here). Did I oversimplify?

like image 950
Roman Avatar asked Feb 21 '10 13:02

Roman


People also ask

Why do we get IOException?

IOException is usually a case in which the user inputs improper data into the program. This could be data types that the program can't handle or the name of a file that doesn't exist. When this happens, an exception (IOException) occurs telling the compiler that invalid input or invalid output has occurred.

What is unhandled exception type in Java?

Java provides complete support to handle the exceptions so that code can run smoothly without termination and provide the desired result. An exception that is not handled is called an unhandled exception and leads to terminating the code before its execution.

What does IOException mean?

IOException is the base class for exceptions thrown while accessing information using streams, files and directories. The Base Class Library includes the following types, each of which is a derived class of IOException : DirectoryNotFoundException. EndOfStreamException. FileNotFoundException.


1 Answers

You should add "throws IOException" to your main method:

public static void main(String[] args) throws IOException {

You can read a bit more about checked exceptions (which are specific to Java) in JLS.

like image 183
Marcin Avatar answered Sep 20 '22 00:09

Marcin