Question

How to tell when FileNotFoundException gets thrown, and how to rethrow it or catch and handle...

How to tell when FileNotFoundException gets thrown, and how to rethrow it or catch and handle it. please provide a coee example. (Java)
0 0
Add a comment Improve this question Transcribed image text
Answer #1

A FileNotFoundException is thrown when we try to open a file which do not exist.It may be possible that the file exists in the PC but not at the path we have provided.So, to avoid this we should provide correct path of the file.

To handle the exception we write it in the try catch block.We open the file in try block,if it throws an exception then the catch block will catch it and the code will be executed which is written in catch block.Thus,it can be easily handled.

Rethrowing exception means notifying the user of the exception occurred. It is done in catch block itself by throw keyword.

It executes the logic written in catch block and also throws the exception.

Code:

// Reading data from a file using FileReader
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
class File
{
   public static void main(String[] args) throws IOException
   {
       // variable declaration
       int ch;

       // check if File exists or not
       FileReader fr=null;
       try
       {
           fr = new FileReader("text");
       }
       catch (FileNotFoundException fe)
       {
           System.out.println("File not found");

throw fe; // throws exception to console so that user can see
       }

       // read from FileReader till the end of file
       while ((ch=fr.read())!=-1)
           System.out.print((char)ch);

       // close the file
       fr.close();
   }
}

Add a comment
Know the answer?
Add Answer to:
How to tell when FileNotFoundException gets thrown, and how to rethrow it or catch and handle...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT