What throws an IOException in Java?
Assume you were:
- Reading a network file and got disconnected.
- Reading a local file that was no longer available.
- Using some stream to read data and some other process closed the stream.
- Trying to read/write a file, but don't have permission.
- Trying to write to a file, but disk space was no longer available.
There are many more examples, but these are the most common, in my experience.
What is a IOException, and how do I fix it?
Java IOExceptions are Input/Output exceptions (I/O), and they occur whenever an input or output operation is failed or interpreted. For example, if you are trying to read in a file that does not exist, Java would throw an I/O exception.
When writing code that might throw an I/O exception, try writing the code in a try-catch
block. You can read more about them here: https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html
Your catch block should look something like this:
try {
//do something
}catch(FileNotFoundException ex){
System.err.print("ERROR: File containing _______ information not found:\n");
ex.printStackTrace();
System.exit(1);
}
Why does this code throw an IOException?
Because the constructor Scanner(File)
throws a FileNotFoundException
which is a sub class of IOException
. Check the javadoc for more details.
Specifying throws IOException
The BufferedReader function readLine() throws an IOException if there is an I/O failure while attempting to read from the input stream. In Java, you must use try catch statements to handle exceptions should they arise:
import java.io.*;
public class addition {
public static void main(String array[])throws IOException
{
InputStreamReader i = new InputStreamReader(System.in);
BufferedReader b = new BufferedReader(i);
System.out.println("Enter first number : ");
// Attempt to read in user input.
try {
int a1 = Integer.parseInt(b.readLine());
System.out.println("Enter second number : ");
int a2 = Integer.parseInt(b.readLine());
int sum = a1 + a2 ;
System.out.println("addition"+sum);
}
// Should there be some problem reading in input, we handle it gracefully.
catch (IOException e) {
System.out.println("Error reading input from user. Exiting now...");
System.exit(0);
}
}
}
What is the difference between throws Exception and throws IOException
This question is really about the basics of Java exception mechanism, but, strangely, I couldn't find an exact duplicate on StackOverflow...
These declarations tell the compiler (and the programmers) which type(s) of exceptions may be thrown by a method.
throws Exception
means that a method may throw any Exception
(either an Exception
instance directly, or any subtype of Exception
, including IOException
).
throws IOException
tells that a method may throw an IOException
, but not, for example, SQLException
.
It is usually a good practice to declare specific exceptions, e.g. throws IOException, ParseException
, instead of just writing throws Exception
.
Java exception handling (IOException)
Your program will only print the Error May be Occured in Input
message if an IOException
occurs. The Javadocs state that this will only happen if an input/output error occurs while getting user input.
Java - Can't handle IOException; must be declared caught or to be thrown
When you add throws Exception to the method signature, that requires that the exception is handled 'upstream' at the point where the method is called.
Something like this:
try{
AnimalStats();
}catch(IOException ex){
// DO SOMETHING
}
However, If you leave the signature silent on this point, you can handle the exception within the method with your try/catch blocks, as you have done. But for that, you need to remove throws from method signature. Like this:
public AnimalStats(){
simulator = new Simulator();
try{
fos = new FileOutputStream("AnimalStats.csv",true);
pw = new PrintWriter(fos);
}
catch(IOException e) {
System.out.println("Error has been caught!");
e.printStackTrace();
}
}
You can use either of the approach.
Related Topics
Stop Scheduled Timer When Shutdown Tomcat
In Which Language Are the Java Compiler and Jvm Written
Collection Interface VS Arrays
What Is Java_Home? How Does the Jvm Find the Javac Path Stored in Java_Home
Are Java Static Calls More or Less Expensive Than Non-Static Calls
Accurate Sleep for Java on Windows
How to Copy Hashmap (Not Shallow Copy) in Java
Which Loop Has Better Performance? Why
How to Retrieve Ip Address from Http Header in Java
@Generatedvalue Polymorphic Abstract Superclass Over MySQL
Cleanest Way to Toggle a Boolean Variable in Java
In Java 8, Why Is the Default Capacity of Arraylist Now Zero
Using an Instance of an Object as a Key in Hashmap, and Then Access It with Exactly New Object
What Is the Equivalent of Java Static Final Fields in Kotlin