0% found this document useful (0 votes)
17 views16 pages

Opps Unit 3 Oops Unit 3 Notes

The document provides notes on Exception Handling and Input/Output Basics for a Master of Computer Application course. It covers topics such as exception hierarchy, throwing and catching exceptions, built-in exceptions, and creating custom exceptions, as well as I/O basics including byte and character streams. Key concepts include the difference between errors and exceptions, types of exceptions, and the use of try-catch blocks for exception handling in Java.

Uploaded by

nayanshi mishra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views16 pages

Opps Unit 3 Oops Unit 3 Notes

The document provides notes on Exception Handling and Input/Output Basics for a Master of Computer Application course. It covers topics such as exception hierarchy, throwing and catching exceptions, built-in exceptions, and creating custom exceptions, as well as I/O basics including byte and character streams. Key concepts include the difference between errors and exceptions, types of exceptions, and the use of try-catch blocks for exception handling in Java.

Uploaded by

nayanshi mishra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

lOMoARcPSD|16655472

OPPS UNIT 3 - oops unit 3 notes

Master of computer application (Dr. A.P.J. Abdul Kalam Technical University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by nayanshi mishra ([email protected])
lOMoARcPSD|16655472

3UNT Exception Handling,


I/O

CONTENTS
Part-1 : Exceptions : Exception. 3-2B to 3-15B
Hierarchy, Throwing and
Catching Exceptions, Built-in
Exceptions, Creating Own
Exceptions, Stack
Trace Elements

Part-2 : Input / Output Basics : 3-15B to 3-25B


Byte Streams and Character
Streams, Reading and
Writing, Console Reading
and Writing Files

3-1 B (MCA-Sem-2)

Downloaded by nayanshi mishra ([email protected])


lOMoARcPSD|16655472

3-2 B (MCA-Sem-2) Object Oriented Programming


Exception Handling, I/O 3-3 B (MCA-Sem-2)

PART- 1
Que3.3. lpifferentiate between errors and exceptions.
Bxceptions : Exception Hierarchy, Throwing and Catching Answer
Rxceptions, Built-in Exceptions, Creating Own Exceptions,
Stack Trace Elements. S.No. Errors Exceptions
1 Errors are exceptional Exceptions are exceptional events
events that occur at the that occur within the program.
Questions-Answers system level.
Long Answer Type and Medium Answer Type Questions 2 Errors are caused by factors Exceptions are typically caused by
outside of the program's problems with input data.,
control, such as insufficient incorrect use of APls, or other
resources or problems with program-specific issues.
Que 3.1l. What is an exception ? How it is handled in Java ? the system configuration.
Answer Errors are usually not Exceptions can be handled by the
3
recoverable and indicate a program using exception handling
1 An exception is an event that occurs during the execution of a program mechanisms.
that disrupts the normal flow ofinstructions. serious problem that cannot
be handled by the program.
2 When an exception occurs, the Java runtime system creates an
exception object, which contains information about the type of exception, Examples of errors include Examples of exceptions include
4.
the location in the program where the exception occurred, and other OutOfMemoryError, NullPointerException,
relevant information. StackOverflowError, and ArrayIndexOutOtBoundsException,
3. Javaprovides a mechanism for handling exceptions, called exception IOException, and SQLException.
LinkageError.
handling.
Errors are not required to be Checked exceptions are required
4 Exception handling allows programmers to write code that can detect 5.
or declared by the
to be caughtwhile
and handle exceptions when they occur, rather than simply caught or declared by the program, unchecked
the program to terminate abnormally.
allowing program.
exceptions do not need to be
5 In Java, exceptions are handled using the try-catch block. caught or declared.
6 Thetry block contains the code that may throw an
catch block contains the code that handles the exception, and the
exception. Java.
Que 3.2. What are errors in Java ? Que 3.4. Explain different types of exceptionsin

Answer Answer
exceptions :
1. In .Java, errors are types of
events that can occur In Java, there are two main types of
during the execution be
of a program that disrupts the normal flow of A. Checked exceptions : checked at compile time and must
2 Errors are exceptional events that occur at instructione 1. These are exceptions that are
usually not recoverable. the system level and are handled by the programmer. Exception class, which is
2 are subclasses of the
Checked exceptionsthe
Examples of errors include Throwable class.
3

4
and LinkageError. OutOfMemoryError, StackOverflowError,
Errors are typically caused by factors 3.
a direct subclass of checked exception must either
A method that throws a its throws clause.
catch the

outside of the exception or declare it in by the


such asinsufficient resourcessor program's control, required to be caught or declared
When an error occurs, it typicallyproblems
iindicates with the system Checked exceptions are
4.

serious problemconfiguration.
5. a IOException,
checked exceptions include
program.
be handled by the program. tha cannot 5 Examples of and ClassNotFoundException.
SQLException,

Downloaded by nayanshi mishra ([email protected])


lOMoARcPSD|16655472

3-4 B (MCA-Sem-2) Obiect Oriented Programming


Exception Handling, I/0 3-5B (MCA-Sem-2)
B. Unchecked exceptions: of
At the top the hierarchy is the Throwable class, which serves as the
1
These are exceptions that are not checked at compile time, and the
1
superclass for allexceptions in Java.
compiler does not enforce thehandling of these exceptions. mhe Throwable class has two direct subclasses: Error and Exception.
2
These exceptions are usually caused by programming errors such 2.
The ErrOr class represents serious problems that cannot be handled by
as null pointer exceptions or dividing by zero.
3.
the application, such as OutOfMemoryError or StackOverflowError.
Unchecked exceptions are not required to be caught or declared by The Exception class represents exceptions that can be caught and handled
the program. 4
4
by the application.
Unchecked exceptions are subclasses of the RuntimeException class,
which is a direct subclass of the Throwable class. 5 Exception has two subclasses: RuntimeException and other checked
5 Examples of unchecked exceptions include exceptions.
NullPointerException, The RuntimeException class represents exceptions that occur due to
ArithmeticException, and IlegalArgumentException. 6
programming errors, such as Null PointerException
In addition tothese two main types of exceptions, there are also
these exceptions, including : subclasses of ArithmeticException.
need to be
C. RuntimeException: 7 These exceptions are unchecked, meaning that they don't
1 This is a subclass of declared or caught.
unchecked exceptions, and it represents subclasses of
programming errors that are not detected by the compiler. 8 The other checked exceptions are represented by various
2 Examples include Exception, such IOException, sQLException, or

NullPointerException, ArithmeticException, and as

ClassNotFoundException.
D
Error:
IndexOutOfBoundsException.
1This is a subclass of unchecked exceptions, and it Que 3.6. Write a short note on uncaught exceptions.
problems that cannot be handled represents serious
by the application.
2 Examples include
E. Exception:This is theOutOfMemoryError and StackOverflowError. Answer
superclass of all exceptions, not caught and handled by
checked and unchecked exceptions. and it includes both 1 An uncaught exception isanexçeption that is
the program.
Que 3.5. Explain the exception hierarchy in Java. program terminates abruptly
2 When an uncaughtexception occurs, the
and an error message is displayed.
Answer exceptions: checked exceptions and
3 In Java, there are two types of
Fig. 3.5.1 represents the exception hierarchy in Java: unchecked exceptions.
not caught and handled by
Throwable 4 When an unchecked exception occurs and is
the program,it becomes an uneaught exception.
problematic because they cause the
5 Uncaught exceptions can be very in lost data or
potentially resulting
Error program to terminate unexpectedly,
Exception other undesirable consequences.
handle
it is important to always
6 To prevent uncaught exceptions, program, either by catching them or
exceptions that can be thrown by a
RuntimeException other checked exceptions declaring them in the throws clause.
programs to ensure that all
7 Additionally, it is important to properly test
potential exceptions are handled correctly.
exceptions. Give example.
NullPointerException Que 3.7, Write a short note on Chained
Fig, 8.5.1. ArithmeticException
Downloaded by nayanshi mishra ([email protected])
lOMoARcPSD|16655472

3-6 B (MCA-Sem-2) Exception Handling, I/0 Object Oriented Programning 37B (MCA-Sem-2)

2.
catch :The catch block is used to handle the exception thrown by the
Answer try block.
1 Chained exceptions, also known as exception chaining, is a technique in finally: The finally block is used to execute code that needs to be
3.
Java that allows one exception to be linked to another exception. executed regardless of whether an exception was thrown or not.
2 This technique is useful in situations where one exception is caused by 4
throw : The throw keyword is used to explicitly throw an exception.
another exception, and it is important tomaintain information about
both exceptions in the stack trace. 5
throws : The throws keyword is used to deciare the exceptions that
might be thrown by a method.
3 outline of
When an exception is thrown, it can be caught and wrapped in a new Outline of an exception-handling block : Following is an
exception, which can then be thrown again. exception-handling block in Java:
4.
an
This new exception contains the original exception as its cause, allowing
both exceptions to be tracked in the stack trace. try l m

5. Ilcode that míght throw an exception


In Java, the Throwable class provides two constructors for creating a
chained exception: }catch (ExceptionTypel el) {
public Throwable(String message, Throwable cause); l code to handle ExceptionTypel
public Throwable(Throwable cause); )catch (ExceptionType2 e2) {
6 The first constructor allows both a message and a cause to be specified lcode to handle ExceptionType2
for the exception, while the second constructor only takes a cause.
)finally (
Example : Il code that will execute
regardless of whether an exception was
public void readFile(String fileName) throws IOException { thrown or not
try |
Ilcode to read the file encloses the code that might throw an
1 In the above block, the try block
Jcatch(FileNotFoundException e){ exception. catch the exception and
throw new IOException("Error reading file:"+ 2. Ifan exception is thrown, the catch block(s) will
fileName, e): handle it appropriately.
catch different types of exceptions.
3 Multiple catch blocks can be used to to be
is used to execute code that needs
1 In this example, if the file specified by the
fileName' parameter is not 4. The finally block is optional and exception was thrown or not.
found, a 'FileNotFoundException' is thrown. executed regardless of whether an
or
execute, even if an exception is thrown
2 Thís exception is caught and wrapped in a new 5. The finally block will always
includes a message and the original'I IOException', which
1FileNotFoundExcept
This new TOException' is then thrown again. ion' cause.
as its
caught.
Que 3.9. Explain about multiple cateh
blocks.
Que 3.8."Java exception handling is managedi via five
Name the five key words and present an outline of
an keywords". Answer
blocks can be used to handle
different types of
handling block with syntax.
Answer
exception- 1. In Java, multiple catch thrown by a try block.
exceptions that might be
exception handling, where each catch
2 This allows for more fine-grained exception.
specific type of
The five keywords used in Java exception handling are : block is responsible for handling a
as follows :
try : The try block is used to enclose the code that might The syntax for multiple catch blocks is
1.
3
exception.
throw an try l
lcode that might throw an exception

Downloaded by nayanshi mishra ([email protected])


lOMoARcPSD|16655472

Obiect Oriented Programming 3-9B (MCA-Sem-2)


3-8 B (MCA-Sem-2) Exception Handling, I/O
}catch (ExceptionTypel e1) { throw new IOException("File not found: "+ fleName);
lcode to handle ExceptionType1
lcode to read the file
}catch (ExceptionType2 e2) {
llcode to handle ExceptionType2
5 In this example, the throw keyword is used to explicitly throw an
}catch (ExceptionType3 e3) { IOException' if the file specified by the fileName' parameter does
Il code to handle ExceptionType3 not exist.
)finally { B. throws :
method
Il code to be executed regardless of whether an exception was 1 throws' is used in a method declaration to indicate that the
thrown may throw one or more exceptions.
using the
When a method declares that it may throw an exception exception
2
4 In this example, the try block contains code that might throw exceptions throws' keyword, the caller of the method must handle the
using its own throws'
of different types, including 'ExceptionTypel, ExceptionType2', and or declare that it may be thrown again
'ExceptionType3. keyword.
5 The catch blocks are used to handle each of these exceptions separately. 3 The syntax for throws' is as follows:
methodName(ParameterType parameterName)
6 If an exception of ExceptionTypel'is thrown, the first catch block will public ReturnType
be executed. throws ExceptionTypel,ExceptionType2
7 If an exception of ExceptionType2 is thrown, the second catch block l method code
will be executed, and so on.
8. The finally' block is used to specify code that should be executed 4 Example of throws
regardless of whether an exception was thrown. throws IOException
9 This block is optional, but it isoften used to perform cleanup operations, public void readFile( StringfileName)
such as closing files or releasing resources. Ilcode to read the file
if (!fleExists(fileName)) (
Que 3.10. Explain about throw and throws
ws found"+ fileName);
keyword with example. throw new IOException("File not
Answer
A. throw :
in the method
throws' keyword is used might
1 throw' is used to explicitly throw an exception from within 5 In this example, the throw an
a method the readFile method
or block of code. signature to declare that
2 When "throw' is used, the program will terminate IOException'. potential
current block and transfer control to the execution of the that it should handlethe
This alerts the caling methoddeclaring it in its own throws' clause.
block that is capable of handling the thrownnearest
6
excentienclosing catch exception by using try-catch or
3. The syntax for throw' is as follows:
throw new ExceptionType("Exception: Q Differentiate between throw and throws.
4 Example of throw: message");
public void readFile(String fileName)
if (!fileExists(fileName)) (
throws IOException l
Downloaded by nayanshi mishra ([email protected])
lOMoARcPSD|16655472

3-10B (MCA-Sem -2) OrientedIProgrammíng


Exception Handling, I/0 Object 3-11B MCA-Sem-2)
e) {
Answer }catch(SomeException
A.
Difference: I/handle the exception
S. No. }finally {
throw' throws this code will always be executed, whether an exception was
1 Definition
throw is used to explicitlythrows' is used to declare thrown or not
throw an
exception the exceptions a method lrelease resources or perform cleanup tasks here
object. might throw.
2. Syntax throw newException();'public void method() code that may throw an
In this example, the try block contains theexception
throws Exception {..)'
7.
exception, and the 'catch' block handles the if it is thrown.
executed regardless of
3. Used in "throw' is used inside a throws' is used in the 8. The finally block contains code that must be can be used to release
and
method to throw an method signature to whether an exception was thrown or not,
exception. declare the exceptions it resources or perform cleanup tasks.
might throw. nested try statements in Java source
4. Exceptions throw' can throw both throws' can onlydeclare Que 3.13. Give an example for
checked and unchecked checked exceptions. file and explain.
exceptions.
5. Answer exceptions in a
Example throw new 'public void. readFile() statements can be used to handle
IOException("File not throws IOException f..' 1 ln Java, nested try try
inner block is nested inside an outer
found"); hierarchical manner, where an
try' block. within the inner
specific handing of exceptions
Que 3.12. Explain about finally' block in Java language. 2 This allows for more mechanism in the outer block.
a fallback
block, while still providing statements in Java:
Answer 3 Here's an example of nested try'
1 In Java, a finally' block is used in conjunction with a try {
handle exceptions that may occur during the execution try-catchhlock to Ilouter try block
of a piece of
code. int[] arr = new int[5];
2 The fnally block is executed after the try block and any
asSociat od try {
"catch' blocks, and regardless of whether an exception Was inner try block ArrayIndexOutOfBoundsException
not. thrown or = 10; // thiswill throw an
3 This means that even if an exception was thrown and arr[5]
(ArraylndexOutOfBoundsException e) {
block, the finally' block willstill be executed. caught by a'catch' catch
} inner try block
exception in ArrayIndexOutOfBoundsException in
the
4 Similarly, if no exception was thrown, the finally' block will / handle the
executed. still be System.out,printin("Caught
e.getMessage());
The 'finally' block is commonly used to release inner try block: "+
5
acquired in the try' block, such as closing a database
ressources that
were
connection
stream, or to perform cleanup tasks such as releasing locks3Or or a file block
}catch (Exception e) exceptionin theouter try
Java resetting
variables. other
I handle any println("Caught Exception in
outer try block: " +
6. Here's an example of how a finally' block can be used in .,
System. out.
try | e.getMessage());
I/ some code that may throw an exception
Downloaded by nayanshi mishra ([email protected])
lOMoARcPSD|16655472

Ohject Oriented Programming 3-13B (MCA-Sem-2)


3-12 B (MCA-Sem-2)
Exception Handling, I/0 viii.ParseException:This exception isthrown when is an
4. in parsing a string into a date or other format
there error
In this example, an outer try' block contains an inner 'try' block.
5. The inner "try' block attempts to access an element outside the bounds ix.
EileNotFoundException :This exception is thrown when afile
of an array, which will throw an specified in a program canrnot be found.
6
'ArrayIndexOutOfBoundsException'
Thisexception is caught and handled within the inner ´catch' block. Tlochecked exceptions :Some of the most commonly used built-in
7 If the inner try' block did not handle the exception, the outer 'catch
B. unchecked exceptions in Java include :
block would catch the exception and handle it accordingly. i ArithmeticException : This exception is thrown when an
8 arithmeticoperation (such as division by zero) results in an error.
By nesting try' statements in this way, you can handle exceptions at
different levels of granularity. NullPointerException:This exception is thrown when aprogram
ii.
tries to access a null object reference.
Que 3.14. Writea short note on built-in exceptions in Java. iii. ArrayIndexOutOfBoundsException:This exception is thrown
with an invalid index.
when an array is accessed
OR
exception is thrown when the
Present an outline of Java's checked exceptions defined in Java iv. ClassNotFoundException : This to find a class that is required by a
language. Java runtime system is unable
program.
Answer when an input/output
V.
IOException : This exception is thrown
1. In Java, built-in exceptions are predefined exception classes that are interrupted.
operation fails or is when an
included in the Java standard class library. IllegalArgumentException :This exeeption is thrown
2 These exceptions are used to handle various error conditions that can vi. to a method.
invalid argument is passed when athread
arise during the execution of a Java program. InterruptedException:This exception isthrown
performing some
vii. sleeping, or
3. By using these built-in exceptions, Java programmers can write
more while it is waiting,
robust and error-tolerant code that can handle unexpected errors and is interrupted
other operation.
exceptions. dava ?
own exception in
4. These exceptions are grouped into two main categories: checked can we create our
Que 3.l5. How OR
exceptions and unchecked exceptions.
detail.
A. Checked exceptions :Following is an outline of some of the commonly
Bxplainuser defined exceptionsin
used checked exceptions in Java : defined
TOEeeption : This exception is thrownwhen there is an error in Answer exceptionsthat are
exceptionsare custom in theirprograms.
reading or writing data from a file or stream. user-defined conditions
1 InJava, speciic error Exception'
SQLExoeption:This exception is thrown when there programmertohandle bvextending eitherthe
ii. is an bythe exceptionsare created
in accessing a database. error User-definedRuntimeException class.
2 a specific
classor the programencounters
exceptionsin
ii. ClassNotFoundException : This exception is thrown whs 4 useful whena
are built-in
.Java Virtual Machine (JV M) cannot nnd a class that is required for 3 User-defined exceptionsnotcovered by any ofthe
execution. condition that is meaningfulerror
error
iss provide more
iv. InterruptedException: This exception thrown when athread Java. we can
customexceptions, handlingprocess.
is interrupted while it is waiting, sleeping, or By defining simplifytheerror prevent errors
from
other operation. performing Some 4.
messagesand custom exceptions can help
easier.
InvocationTargetException : This exception is Additionally, using andmakedebugginguser-definedexception that
an exception occursduring the thrown when
invocat on ofaamethod or constructor. 5.
beingsilently
ignored
exampleshowhow
to define a
vi. NoSuchMethodException : This exception is thrown when Following
extends the Exception'class:
requested method cannot be found. a
: This exception is
vii. NoSuchFieldException
found.
requested field cannot be
thrown when a
Downloaded by nayanshi mishra ([email protected])
lOMoARcPSD|16655472

3-14 B (MCA-Sem-2)
Exception Handling, I/o Object Oriented Programming
3-15 B(MCA-Sem-2)
public class InvalidlnputException extends Exception ( also be used to improve error
Stack traces can handling and provide
public InvalidInputException() 9 more meaningful error messages to users.
super();
PART-2
public InvalidInputException(String message)
Input ! Output Basics Byte Streams and Character Streams,
super(message); Reading and Wríting, Console Reading and Writing Files.

7 In the Questions-Answers
example above, we define a custom exception class
InvalidInputException' that extends the 'Exception' class. called
8 We provide two Long Answer Type and Medium Answer Type Questions
constructors, one that takes no arguments and one that
takes a String' argument that will be used as the
9. We can use this custom exception message.
exception in our code like any other exception. Que 3.17. What are streams ? What are the uses of
streams in
Que 3.16. Explain stack trace
elements in detail. Java ? What are the two types of streams ?
nswer
Answer
1. In Java, a stack trace is a
specific point in time duringtextual
Streamns :
representation of the call stack at a
program
A.
In Java, a stream is a sequence
of data that can be read from or
2 It shows the execution. 1

thrown or ansequence
of method calls that led written to.
error up to an exception being output operations in Java.
3 A stack trace is
occurring. 2 Streams are used to perform input and
useful for debugging purposes uses of streams in Java are:
information about where an error occurred and howbecause it B. Uses of streams:The main connections,
through the program. it was provides Reading and writing data to and from fles, network
4. Each line in the stack trace propagated 1
and other sources and
destinations.
using ilters, such as converting
order in represents
a method call, and the
the lines shows the Manipulating and transforming data decompressing
which the methods were called order of
2 compressing and
formats or
5. Each line in a stack trace
contains the following data between different
i The name of the class that contains the informatinn data.
amounts of data.
The name of the method that was called. method that was called. 3 Parallel processing of large
üi. The line number in the source code where C Types of streams :
the categorized into two types:
(if available). method call occurred 1 Java streams are read and write
Byte streams are used to
ív, Ifthe method was called from another class, Byte streams: files. Byte streams
i. images, audio, and video utputStream'
the name of binary data, suchas and
and method that called it.
the class the InputStream'
6 Stack trace elements can be accessed are implemented using
used to read
7.
"Throwable.getStackTrace()' method.
This method returns an
programmatically using the
array 'Stack'TraceElement'
of
ii.
classes.
Character streams :
write text data,
Character streams are
characters. Character
such as strings and Reader' and Writer
and implemented using the
8
which represents a single line in the stack trace.
using
By stack
traces,
we can gain insight
into how errors
objects, each of streams are
classes. perform input
are
through our programs and identify the root cause of problem streams and character streams are used todifferent types
propagated 2 Both byte
and output
of data.
operations in Java, but they
operate on

Downloaded by nayanshi mishra ([email protected])


lOMoARcPSD|16655472

3-16 B (MCA-Sem-2) Exception Handling, I/0 Object Oriented Programming 3-17B (MCA-Sem-2)
Output streams are used to write data to various destinations such as
3 When working with text data, character streams should be used
while when workingg with binary data, byte streams should be used
2. Gles, network connections, and user output.
The OutputStream' class defines several methods that can be used to
Que 3.18.What is InputStream ? Present an outline of the methods 3
write data to the stream.
defined by InputStream. Here's an outline of sorne of the key methods defined by 'OutputStream':
4
Answer 1
void write(int b): Writes a single byte of data to the output
1.
stream. The byte is specified as an integer value between 0 and 255.
In Java, an InputStream is an abstract class that represents a stream of
bytes from which data can be read. ji. void write(byte[J b) :Writes the entire byte array bto the output
2 stream.
Input streams are used to read data from various sources such as
network connections, and user input.
files len bytes of data
iii. void write(bytel] b, int off, int len): Writesthe output stream.
from the byte array b, starting at the offset off, to
3 The InputStream' class defins several methods that can be
read data fromn the stream.
used to
iv. void flush) :Flushes any buffered output data to the underlying
4 Here's an outline of some of the key methods defined by stream.
InputStream' : system
int read() :Reads a single byte of data V. void close() : Closes the output stream and releases any
from
returns it as an integer value between 0 and the input stream and resources associated with it.
255. If the end of the functionahty for writing data to an
streamn has been reached, returns- 1. 5. These methods provide a basic set of
i int read(byte[] b): Reads up to output stream.
input stream into the specified byteb.length bytes of data from the Illustrate
array b. Returns the number of on byte streams in Java.
bytes read, or -1 if the end of the stream has been reached. Que 3.20. Write a short note
ii. int read(byte[] b, int off, int
from the input stream into the len): Reads up to len bytes of with an example.
offset off. Returns the number specified byte array b, startingat data
of bytes read, or -1 if the end the Answer
binary data from and to
stream has been reached. of the
1. In Java, byte streams are used to read and write
iv. longskip(long n) : connection or other source.
Skips over and a file, network
from the input stream. Returns the discards up to n bvtes ofdata useful when dealing with raw
data such as images,
number of bytes 2. Byte streams are
number skipped.
int available() : Returns an estimate of the audio, and video fles. and 'OutputStream,
can be read from the input stream
without of bytes that classes, Input Stream'
can be used to check if blocking. This 3. Java provides two abstract
the stream.
there is any data available to be readmethod
from
streams.
as the basis for byte
to use a byte stream to
read data from a
vi. void close() : Closes the input
stream and Following example shows how :
file
file and write it to another
5
resources associated with it.
These methods provide a basic set of functionality
releases any system
import java.io.*;
for public class ByteStreamExample
an input stream. reading data from String] args) throws
IOException (
Que 3.19. What is OutputStream ? Present public staticvoid main( null;
an FilelnputStream inputStream =
methods defined by OutputStream. outline of the Stream outputStream =null;
FileOutput
Answer try { FilelnputStream("input.txt):
new FileOutputStream("output.txt");
inputStream ==new
outputStream
1 In Java, an OutputStreamis an abstract class that
of bytes to which data can be written. represents stream
aa
int c;
inputStream.read()) != -1) {
while ((c =

Downloaded by nayanshi mishra ([email protected])


lOMoARcPSD|16655472

3-18 B(MCA-Sem-2)
Exception Handling, I/O Object Oriented|Programming
3-19B (MCA-Sem-2)
)finally (
outputStream.write(c); FileWriter writer =null;
try {
if reader =new FileReader(
(inputStream != null) { writer =new "input.txt");
inputStream.close(); int c; FileWriter("output.txt");
if while ((c= reader.read)) != -1){
(outputStream != null) ( writer.write(c);
outputStream.close); t u m
}finally {
if (reader != null) {
5
In this reader.close);
example, we create a
named input.txt".
6
We then create a FileInputStream to
read data from a file if (writer != null) {

7
named "output.txt".
We usea 'while' FileOutputStream
to write the
data to a new file
writer.close);

time, and write itloop to read data


from the
stream usinginput
to the
Finally, we close the inputoutput the 'wstream one
8
and output rite' method.byte at a
Que 3.21. | streams to free up system
Write short note on
a resources. 6 In this example., we create a FileReader' to read text data from a file
Illustrate with an example. character streams in Java. named "input. txt".
new file named
Answer 7 We then create a FileWriter to write the data to a
1 In Java, "output.txt".
character streams are used to read and
to a file, We use a 'while' loop to read data from the
input stream one character
2 network connection, or other source. write text data from and at a time, and write it to the output stream using the write' method.
Character
dealing withstreams
free up system resources.
text fileshandle character data, making them useful
or other
9. Finally, we close the input and output streams to
3.
Java provides two
abstract
text-based data. when Write ashort note on standard
streams in Java.
character streams. classes, Reader and Que 322.
4
Character
Writer, as the basis for
streams also provide additional
writing text data, such Answer output streams
as 'readLine' and methods for reading and are pre-defined input and
easier tO work with 1 In Java, standard streams or terminal where the
5.
Following example
text-based data.
shows
from a file and write it to how to use acharacter
writeString,
which make it that are automatically
connected
Java program is running.
to the console
especially
part of Javaprogramming,
another file: streamn to read data 2 Standard streams are an important
import java.io.*; for command-line appications.
read and write text data.
public class CharacterStreamExamplel and convenient way tooutput streams for every
3 They provide a simple custom input and
public static void main(Stringll args) without having to create
throws IOException program.
FileReader reader =null; 4 There are three standard
streams :

Downloaded by nayanshi mishra ([email protected])


lOMoARcPSD|16655472

3-20 B (MCA-Sem-2)
Exception Handling, I/0 Object Oriented Programming 3-21 B MCA-Sem-2)
System,in : The standard input stream, which is used for reading publicclass ReadFileExample l
input from the user via the console or terminal.
ii. public static void main(String args) (
System.out:The standard output stream, which is used for writing
output to the console or terminal. tryl
ii. System.err: The standard error FileInputStream filelnput new
stream, which is used for writing
error messages and other diagmostic FilelnputStream("file.txt");
terminal. information to the console or
byte] buffer = new byte[10241;
5
Standard streams are instances of the InputStream' and int bytesRead = 0;
classes in Java, respectively. PrintStream'
6
They are typically used for simple while ((bytesRead =filelnput.read(buffer)) !=-1){
command-line
input from the user and produce output programs that require System.out.printin(new Stringtbuffer, 0, bytesRead);
on
the console or terminal.
Que 3.23. Explain in detail about
the following with sample filelnput.close();
program :
Reading from a file }catch (IOException e) {
ii.
Writing in a file e.printStackTrace);
OR
How to perform reading and writing files ?
Answer
Explain with example.
PilelnputStream object to read
i. Reading from a file: In the example above, we create a
5 "file.txt.
1 In Java, the datafrom a file called read a chunk of data
FilelnputStream class is used for
from a file. reading binary data 6 We then createa byte array of size 1024 to
It is an input stream that from the file. the end
into the buffer until object.
2
reads bytes from a file in a method to read data
3 To read data from a file
using file'system. 7 We use the readO and then we close the
FileInputStream
these steps : FilelnputStream,
you need tofollow ofthe file is
reached.
data that we read from
the file to the
console.
Sten 1: Create an instance of the Finally, we print the
8
the path of the file that you wantFilelnputStream
to read as an
class and pass Writing in a file : usedfor writing
binarydata
argument FileOutputStreamclassis
to its ii.
constructor.
InJava, the
ina file system.
Step 2 :Create a byte array of afixed size to read a 1.
chunk ofAnte toa file. bytes to a fle
from the file.
output stream that writes
FileOutputStream,you need to
follow
Step 3: Use the read()) method of the 2. It is an using
ile
data from the file into the byte array. FilelnputStream
This method class to read 3. To write datato a
these steps: Streamclass and
ofthe FleOutput an argument to its
pass

beenreturns
number of bytes read, or -1ifthe endof the fle has the an instance as
Step l: Create file that you want to write createdautomatically.
Step4: Continue reading data from the file until the reached.
read) method the path of
the be
doesn'texist, itwill datathat youwant to
returns -1. constructor. Ifthefile that containsthe
Step5:Close the FileInputStream object usinggthe byte array
close() Step2: Createa FileOutputStream class to
to release any system resources associated with it. method write to the file.
write) method of the
writes theentire
array to the
4 Following example demonstrates how to use Step 3: Use thethe fle. This method
read datafromafile:
import java.io.*;
FileInputStream to write the datato
fle. FileOutputStreamobject using
theclose()
with it.
method

Step 4:Closethe resourcesassociated


any system
to release

Downloaded by nayanshi mishra ([email protected])


lOMoARcPSD|16655472

3-22 B (MCA-Sem-2) Object Oriented Programming 3-23B (MCA-Sem-2)


Exception Handling, I/o
4
Following example demonstrates how to use FileOutputStream t Here's a sample program that demonstrates how to read input from a
class :
fle using the Console
write data to a file: 5.

import java.io.*; import java.io.BufferedReader:


public class WriteFileExample import java.io.Console:
public static void main(String] args) { import java.io. File:
try { import java.io.FileReader:
File OutputStre am fileOutput import java.io.IOException;
new
FileOutputStream("file. txt"); public class ConsoleFileReadingExample{
String data = T'his is some data that will be public static void main(Stringl args) !
to a file.": written
Console console = System.console);
byte] bytes = data.getBytes); if (console != null){
fileOutput. write(bytes); console.printf("Enter the file name:
fileOutput.close();
Jcatch String fileName = console.readline):
(IOException e) { try {
e.printStackTrace); File file = new Filefile Name);
FileReader fileReader=new FileReader(file);
BufferedRe ader bufferedReader new

BufferedReader(fileReader);
5 In the example
write data to a fileabove, we create a
6. We then create a
called "ffle.txt". FileOutputStream obiect to String line= nul
while ((line
bufferedReader.readLine) nul){
write to the file.
string that
contains some data that we want to console.printf("%s\n", line);
7 We convert this string to a
and then we use the write()byte array using the getBytes() method. bufferedReader.close);
method to write
8. Finally, we close
the File OutputStream object.the data to the Gle }catch (IOException e) {
Que 3.24. Explain about reading from files e.print StackTrace);
with sample program. using Console class
Answer
1 In Java, you can use the Console class to read input

2
and the File class to read input from a file. from the coonsole above, we first create
an instance of the Console
class
Console class is only available if the program is run 6. In the example
from a System.console) method. using the
command prompt. using the name ofthe fle to read
3 If the programis run from an IDE or other environment console or
7 We then prompt the user to enter the
methods ofthe Console class.
provide a console, the System.console() method will : that does not printf) and readLine) to represent the
input fle.
return instance of the File class of the FileReader class
usingnull,
program will not be able to read input from the console create an
class. th and the
the Console We then argument to the
constructor
constructor of the
and pass it as an FileReader object to the
4. In that case, you can use other methods such as 9 We then pass the
BufferedReader to read input from the file.
SScanner or
BufferedReader class.

Downloaded by nayanshi mishra ([email protected])


lOMoARcPSD|16655472

3-24 B MCA-Sem-2)

10. The while loop reads each line of the file


the BufferedReader class, and prints it to
method of the Console class.
usingExceptreadLine
the the
ion HandiA
console
Object Oriented Programming
To the example above, we first
3-25 B (MCA.Sem-2)

11. Finally, we close the Buffered Reader using the rin 3. create an instance of the Consal e class
using the System.console) method.
resources associated with it. object to release 4
We then prompt the user to enter the
intf) and readLine) methods ofthename of thefile to write nsing the
Que 3.25. Explain about
any syst We then create an instance of the
Console class.
writing in a file using 5
Fle. and pass it as an argument toFileWriter class to write at a to the
sample program. Console class with class.
the constructor of the Rle Writer
Answer 6.
The while loop reads each line of input from the user using
thereadLine)
1 In Java, you can use the method of the Console class, writes it to the file using the wrie0 method
the File class to write Console class to write output to of the File Writer class, and appends a newline character at the end of
output to a the console and each line.
2
Here'ssa sample program that file. The loop continues until the user types "quit".
using the Console class: demonstrates how to write 7.
Quant
import java.io.Console: output to afile 8 Finally,we close the File Writer object to release anysystnresources
associated with it and print a success message to the consle using the
import java.io.FileWriter; printf() method of the Console class.
import java.io.IOException;
public class ConsoleFileWritingExample{
public static void
Console consolemain(Stringl args) {
if
=
(console != null) System.
{ console(0; Sep
console.printf("Enter the file name: ");
String fileName console.readLine);
try
File Writer
fileWriter = new File
console.printf(Enter Writer(fileName);
text (type 'quit' to
exit):\n";
String line = null;
while
(!(line
consolfilee.rWriter.
eadLinwe().rite(line
equalsIgnore
+ *\n");
Case("quit'")
)catch
fileWriter.close); saved successfully!\n;
console.printf("File
(IOException e)
e.printStackTrace();

Downloaded by nayanshi mishra ([email protected])


lOMoARcPSD|16655472

Object Oriented Programming SQ-11 B (MCA-Sem -2) SQ-12 B (MCA-Sem-2)


2 Marks Questions
by another exception, and it is
important to maintain information
about both exceptions in the stack

3 UNIT
Exception Handling,
(2Marks Questions)
3.7.Name the five keywords used in Java
AnE: The five keywords used in Java
1. try
2. catch
3. finally
trace.

exception
exception handling.
handling are:

4. throw
5. throws

3.1. What is an 38. Discuss throw and throws


exception ? keyword.
Ans: An exception is an event that Ans.
occurs during the execution of a
program that disrupts the normal flow of instructions. A. throw :throw is used to explicitly throw an
exception from
a method or block of code. within
32. What is exception handling ? B. throws : throws' is used in a mnethod
declarationto indicate that
Exception handling is the process of detecting and the method may throw one or more exceptions.
exceptions in a way that allows a program to responding to
continue
without terminating abruptly. In Java, executing 3.9. Explain about finally' block în Java language.
the try-catch block. exceptions are handled uaing OR
3.3. What are errors in Java? What is the purpose of finally clause ?
H In Java, a finally block is used in conjunction
block to handle exceptions that may occur duringwith
Ans. In Java, errors are types of a try-catch
of a program that disruptsevents that can occur during the
the normal flow execution a piece of code.
the execution of
are of instructions. Errors
exceptional events that occur at the system level
not recoverable. and are usually 3.10. What is the use of assert keyword ?
34. AE The 'assert keyword in Jav is used to eheck certain conditions
Explain different types of during runtime and throw an 'AssertionError if the eondition is
Ans. In Java, there exceptions in Java.
are two main types not met. It is primarily used for debugging and testing purposes,
A. Checked exceptions of
exceptions: and alows developers to check the correctness of their assumptions
B. Unchecked exceptions
and catch errors early in the development process.
In addition tothese two main types of
C. subclasses of these
RuntimeException
D. Error
exceptions, includingexceptions,
: there are also 311. What are built-in exeeptions in Java ?
A In Java, built-in exceptions are predefined exception classes that
E. Exception are included in the Java standard class hbrary. These exceptions
are used to handle various errog conditions that can arise during
35. What is the execution of a Java program.
uncaught exception ?
As An uncaught
by the exception isanan excption that is not
program.
3.12. Explain user defined exceptions in Java.
When uncaught caught and handled A n Java, user-defined exceptions are eustom exceptions that are
terminates abruptly exception
and an error message is
occurs, the program defined by the programmer to handle specific error conditions in
36. What is displayed. their programs. User-defined exceptions are cereated by extending
An Chained chained exception ? either the Exception' elass or the RuntimeExeeption' class.
exceptions,
in Java that allows
also
one known astoexception
This technique is usefulexception chaining, is a technique
in situationsbe linked to another exception.
313. Define runtime exceptions.
unchecked exception in Java that
where one exception is Anss Runtime exceptions are a type ofof a program. They are called
occurs during the execution
caused
Downloaded by nayanshi mishra ([email protected])
lOMoARcPSD|16655472

Object Oriented Programming sQ-13 B (MCA-Sem-2)


sQ-14 B(MCA-Sem-2) 2 Marks Questions
"unchecked" because they do not need to be declared in the method
signature or caught by the calling method, unlike checked public class
exceptions which must be declared or handled. Runtime exceptions FilelnputStreamExample
public static
{
void main(Stringl args) {
are typically caused by errors in the logic or flow of aprogram, such try |
as dividing by zero, accessing an invalid index in an array, or trying
tocast an object to an incompatible class. FileInputStream inputStream new
FilelnputStream("input. txt");
3.14. What is stack trace element ? int data = inputStream.read(0;
while (data!=-1)
Ans. In Java, a stack trace is a textual representation of the call stack at.
a specific point in time during program execution. It shows the System.out.print(char) data);
sequence of method calls that led up to an exception being data = inputStream.read();
or an error occurring. thrown
inputStream.close0;
3.15. What are streams ? What are the uses of }catch (IOException e)
streams in Jaya ? e.printStackTrace);
Ans: In Java, a stream is a sequence of data that
can be read fromn or
written to. Streams are used to perform input and output
in Java. operations
}
3.16. What are the uses of streams in
Java ?
Ans. The main uses of streams in Java are: 3.20. What is OutputStream ?
1. Reading and writing data to and Ans: In Java, an OutputStream is an abstract class that represents a
from files, network connections,
and other sources and destinations. stream of bytes to which data can be written. Output streams are
2. Manipulating and used to write data to various destinations such as files, network
transforming data using filters, such as converting
data between different connections, and user output. The OutputStream' ciass defines
data. formats or compressing and decompressing several methods that can be used to write data to the stream.
3. Parallel processing of large amounts of data.
3.21. How character streamsare defined?
3.17. What are the two types Ans In Java, character streams are defined using the Reader and Writer
of streams ?
Ans. Java streams are abstract classes and their concrete subelasses. The Reader' and
1. categorized into two
Byte streams : Byte types : Writer classes provide a set of methods for readng and writing
data, such as images,streams are used to read and
audio, and video files. Byte write binary characters, respectively.
implemented using the streams are
Character streams :InputStream'
Character
and OutputStream' classes. 3.22. What are standard streams in Java ?
write text data, such as strings and streams are used to read and Ans: In Java, standard streams are pre-deâned input and output streams
characters. that are automatically connected to the console or terminal where
are implemented using the
Reader' and WriterCharacter
classes.
streams the Java program is running.
3.18. What is
Ans In Java, anInputStream is
?
InputStream
of bytes from an
data canabstract class that represents a
read data fromwhich
various
be read. Input stream
streams are used to
and user input. The sources such as files, network
'InputStream'
that can be used to read class connections,
data from the defines several methods
stream.
3.19. Give an
example for
A FileInputStream'
Example . fromreading
of readingdata
data from
a file using
files using
import java.io.*;
'FileLnputStream' in Java:
Downloaded by nayanshi mishra ([email protected])

You might also like