9/180: File Processing and Exception Handling in Java

Navneet Ojha
4 min readMar 27, 2021

--

Today is 9th day of 180 days challenge. Though I was free the whole day, still procrastinating all the time but somehow managed to have few hours of learning. So today I did the basics, that understanding the language from the start. Though I have understood many things which previously I find difficult to do, but here I will be posting about the file processing and Exception Handling only.

Starting with the very basic concept how java reads the user input. Let’s begin

//This is the basic first step to read user input. We pass System.in as a parameter which is of type InputStream

Scanner input = new Scanner(System.in)

System.out.println(“Enter some text:”), at this point it will prompt for a user input. And when you input some text, it’s very next step is to read the input.

String enteredText = input.nextLine();

//Below line of code with print the input entered by user and read by the java program

System.out.println(enteredText);

Let’s do it the same way to read input from a file. Let’s say I have some random file with text xyz in it.

File file = new File(“myfile.txt”);

//The above line must be given an error and that is because this class extends the exception class and it can have the fileNotfound exception. To correct this thing we can include the whole code inside the try catch block and the error would disappear.

Scanner input = new Scanner(File); // here is the call to different constructor with parameter as input type file.

while(input.hasNextLine()){

String line = input.nextLine();

System.out.println(line);

}

try{

//place the whole code we have written above, from file creation to reading file here.

}catch(FileNotFoundException e){

e.printStackTrace();

}

for testing the exception you can remove the file from that place and see the result it will print the stack trace. You can also print System.out.println(“File not found”) instead of e.printStackTrace() to be more user friendly.

Now talking about the exception handling, Let’s create a class to see how exceptions work

public class MyFileUtils {

public int subtract10FromLargeNumber(int number) throws Exception{

if(number < 10){

throw new Exception(“Number should be More than 10”);

}

return number -10;

}

}

Now lets create object of the class and checkout the functioning

MyfileUtils myUtils = new MyFileUtils();

myUtils.subtract10fromLargeNumber(20);

//the above line of code will display an error to either add try catch block or throw exception. Because this function throws the exception and we can fix it making the line of code inside the try catch block.

Now let’s say we want to create our own custom type exception and we can do it by extending the exception class.

Public class FooRuntimeException extends Exception{

public FooRuntimeException(String message){

super(message);

}

}

Now our customized exception class is created we can now use it instead of

throw new Exception()

throw new FooException()

Now lets read the file using buffer reader

Buffered FileReader with Try Catch and Finally

File file = new File(“myfile.txt”);

try{

//The below line of code file not found exception

FileReader fileReader = new FileReader(file);

//The below line of code throws IO exception and if we will don’t catch it inside the try catch block it will keep on showing an error.

BufferedReader bf = new BuffueredReader(fileReader);

String line = bf.readLine();

while(line !=null){

System.out.println(line);

line = bf.readLine();

}catch(FileNotFoundException e){

System.out.println(“File Not found”); }

catch(IOException e){

System.out.println(“problem reading file”); }

//finally block is required so as to close the bufferreader and filereader in all the situations, weather the system thrown the exception or not finally block will always compile

finally{

try{

//The below line of code basically gives an error if we don’t add it inside the try catch block, because it throws an exception

bf.close()

}catch(IOException e){ System.out.println(“Problem in closing the file”)}

}

Exceptions should be used only for exceptional conditions.

Try with Resources and AutoCloseable Interface

I don’t want to use finally block for closing the resources and I can reduce my code by using try block with resources and i will pass filereader and bufferedreader objects inside as the resources and it will get automatically closed as its inherited class use autocloseable interface so we don’t have to do anything.

//using the below line will close both the objects and therefore no more need of finally block

try(FileReader fileReader = new FileReader(file); BufferedReader bf = new Bufferedreader(fileReader)){

//rest of the code will remain same just the try is now having the parameters or we can say resources.

}catch……

Let’s see how Autocloseable works

class MyClass implements Autocloseable{

@Override public void close throws Exception{System.out.println(“Closing”);}

}

public class Application2{

public static void main(String[] args){

try(MyClass mycls = new MyClass();){

}catch(Exception e){e.printStackTrace();}

}

}

The output of Application2 will be printed as Closing

--

--

Navneet Ojha
Navneet Ojha

Written by Navneet Ojha

I am Indian by birth, Punjabi by destiny. Humanity is my religion. Love to eat, travel, read books and my million dreams keep me alive.

No responses yet