Opps Unit 3 Oops Unit 3 Notes
Opps Unit 3 Oops Unit 3 Notes
CONTENTS
Part-1 : Exceptions : Exception. 3-2B to 3-15B
Hierarchy, Throwing and
Catching Exceptions, Built-in
Exceptions, Creating Own
Exceptions, Stack
Trace Elements
3-1 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
serious problemconfiguration.
5. a IOException,
checked exceptions include
program.
be handled by the program. tha cannot 5 Examples of and ClassNotFoundException.
SQLException,
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
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
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 =
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);
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
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.
3-24 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();
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