In this tutorial I am going to explain one of the most common Java exception that is well known by all the Java developers. IOExceptions are thrown when there is any input / output file operation issues while application performing certain tasks accessing the files. IOException is a checked exception and application developer has to handle in correct way.
IOException has many sub classes that are specific in nature. That means, when your application searching to read a file, if the file is not found that there is a ileNotFoundException to be thrown. FileNotFoundException is a subclass of IOException. Like this there are many subclasses defined in exception packages for handling the specific scenarios.
Few of the well known classes are:
- FileNotFoundException
- EOFException
- SSLException
- UnSupportedEncodingException
- SocketException
IOException Example
Here is simple example for IOException:
import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class ExceptionExample { public FileInputStream testMethod1(){ File file = new File("test.txt"); FileInputStream fileInputStream = null; try{ fileInputStream = new FileInputStream(file); fileInputStream.read(); }catch (IOException e){ e.printStackTrace(); } finally{ try{ if (fileInputStream != null){ fileInputStream.close(); } }catch (IOException e){ e.printStackTrace(); } } return fileInputStream; } public static void main(String[] args){ ExceptionExample instance1 = new ExceptionExample(); instance1.testMethod1(); } }
When you run the above program where there is no file present in the file system, you would get the following exception:
java.io.FileNotFoundException: test.txt (The system cannot find the file specified) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.<init>(FileInputStream.java:138) at logging.simple.ExceptionExample.testMethod1(ExceptionExample.java:12) at logging.simple.ExceptionExample.main(ExceptionExample.java:30)
This is one of the IOException, but depends on the different problems in reading the file, your application may throw some other IOExceptions.
If you look at the above code:
- The above code tries to read the file test.txt from the file system.
- It throws the FileNotFoundException, that is a subclass of IOException
- IOException and all the subclasses are checked exceptions
- If you create a file names test.txt in the correct path and run the above program, you will not get any exception.