In: Computer Science
Whenever an exception arises, it terminates the program
execution, which means it stops the execution of the current java
program.
a) Identify and explain how the remedy for the exception is
considered.
b) Implement the above-identified remedy in the java program to
overcome the problem raised in the exceptional case when we try to
open and close the files.
a)
The remedy for exception is to handle them.
In java we can handle them with try-catch block.
Using try-catch block handles the exception.
in the try block we write the required code.
In the catch block we write the appropriate message to
display.
try block will have exception expected lines.
if there any exception raised then appropriate catch block will be
executed.
b)
Opening and closing file exceptions will be in
IOException class.
So we need to write the open and close file statements in try block
and IOException is catched in catch block.
Here the filereader tries to open the file and then buffer readers
takes the file opened.
Then we try to close the file by closing the bufferreader.
If there any exceptions the catch executes.
CODE OF IMPLEMENTATION OF FILE STREAMS:
iimport java.util.*;
import java.lang.*;
import java.io.*;
class fileExceptns
{
public static void main(String[] args)
{
//try block where we write the
opening and closing file lines of code.
try
{
//we here try to
open a txt file.
FileReader
reader = new FileReader("svsc.txt") ;
BufferedReader in = new
BufferedReader(reader) ;
System.out.println("File is opened
successfully");
in.close();//here we try to close
the file bufferreader.
System.out.print("File is closed
successfully");
}
//if there any input output
exception in the try block then this
//block executes and prints the
exception.
catch (IOException e)
{
//printing the
IO exception.
System.out.println("The exception is "+e);
}
}
}
CODE ATTACHMENTS:
OUTPUTS:
The first output is there is no file then so the exception file notfound is preinted.
The second output i have created the file so it printed successful.
All IO exceptions are handled in this.
Please do comment for any queries.
PLease like it.
Thank You.