42
UNIT III EXCEPTION HANDLING AND I/O
Java FileWriter Example
In this example, we are writing the data in the file testout.txt using Java FileWriter class.
package com.javatpoint;
import java.io.FileWriter;
public class FileWriterExample
{
public static void main(String args[])
{
try
{
FileWriter fw=new FileWriter("D:\\testout.txt");
fw.write("Welcome to javaTpoint.");
fw.close();
}catch(Exception e){System.out.println(e);}
System.out.println("Success...");
}
}
Output:
Success...
testout.txt:
Welcome to java.
Part A Question Bank
1.a.What is exception?
Or
1.b.Define Exception?
An exception is an event, which occurs during the execution of a program, that disrupts
the normal flow
2.a.What is error?
Or
2.b.Define error?
An Error indicates that a non-recoverable condition has occurred that should not be
caught. Error, a subclass of Throwable, is intended for drastic problems, such as OutOf-
MemoryError, which would be reported by the JVM itself.
3.a.Which is super class of Exception?
Or
3.b.What is super class of Exception?
CS8392-Object Oriented Programming
43
UNIT III EXCEPTION HANDLING AND I/O
4.a.What are the advantages of using exception handling?
Or
4.b.Write the uses of exception handling.
-
ment techniques:
Grouping Error Types and Error Differentiation.
5.a.What are the types of Exceptions in Java?
Or
5.b.What are the classification of Exception?
There are two types of exceptions in Java, unchecked exceptions and checked excep-
tions.
Checked exceptions: Achecked exception is some subclass of Exception (or Exception
itself), excluding class RuntimeException and its subclasses. Each method must either handle all
checked exceptions by supplying a catch clause or list each unhandled checked exception as a
thrown exception.
Unchecked exceptions: All Exceptions that extend the RuntimeException class are
unchecked exceptions. Class Error and its subclasses also are unchecked.
6.a.Why Errors are not checked?
Or
6.b.What is the reason errors are not checked?
An unchecked exception classes which are the error classes (Error and its subclasses) are
exempted from compile-time checking because they can occur at many points in the program and
recovery from them is difficult or impossible. A program declaring such exceptions would be
pointlessly.
7.a.How does a try statement determine which catch clause should be used to handle an exception?
When an exception is thrown within the body of a try statement, the catch clauses of the
try statement are examined in the order in which they appear. The first catch clause that is capable
of handling the exception is executed. The remaining catch clauses are ignored.
8.aWhat is the purpose of the finally clause of a try-catch-finally statement?
Or
8.b.What is the use of finally class?
The finally clause is used to provide the capability to execute code no matter whether or
not an exception is thrown or caught.
9.a.What is the difference between checked and unchecked Exceptions in Java?
Or
9.b.State the differences of checked and unchecked Exceptions in java.
All predefined exceptions in Java are either a checked exception or an unchecked excep-
tion. Checked exceptions must be caught using try catch () block or we should throw the exception
using thr
10.a.What is the difference between exception and error?
Or
10.b.State the differences for exception and error.
The exception class defines mild error conditions that your program encounters. Excep-
tions can occur when trying to open the file, which does not exist, the network connection is
disrupted, operands being manipulated are out of prescribed ranges, the class file you are interested
in loading is missing. The error class defines serious error conditions that you should not attempt to
recover from. In most cases it is advisable to let the program terminate when such an error is
encountered.
CS8392-Object Oriented Programming
44
UNIT III EXCEPTION HANDLING AND I/O
11.a.What is the catch or declare rule for method declarations?
Or
11.b.State the rule for method declaration.
If a checked exception may be thrown within the body of a method, the method must
either catch the exception or declare it in its throws clause.
12.a.When is the finally class of a try-catch-finally statement executed?
Or
12.b.What is the use of finally class?
The finally clause of the try-catch-finally statement is always executed unless the thread of
execution terminates or an exception occurs within the execution of the finally clause.
13.a.What if there is a break or return statement in try block followed by finally block?
If there is a return statement in the try block, the finally block executes right after the
return statement encountered, and before the return executes.
14.a.Write short notes on throwable class.
Or
14.b.Define Throwable class
The Throwable class is the superclass of all errors and exceptions in the Java language. It
contains a snapshot of the execution stack of its thread at the time it was created. It can also contain
a message string that gives more information about the error. The Exception class inherits all the
methods from the class Throwable.
15.a.Write short notes on Exception class.
Or
15.b.Define Exception class.
Java allows the user to create their own exception class which is derived from built-in
class Exception. The Exception class inherits all the methods from the class Throwable.
Two commonly used constructors of Exception class are:
Exception() - Constructs a new exception with null as its detail message.
Exception(String message) - Constructs a new exception with the specified detail message.
Syntax:
class User_defined_name extends Exception{
}
16.a.How is custom exception created?
Or
16.b.State the syntax to create exception.
The user defined exception is created by extending the Exception class or one of its sub-
classes.
Example:
class MyException extends Exception
{
public MyException( )
{
super();
}
Public MyException(String s)
{
super(s);
}}
17.a.What are the different ways to handle exceptions?
CS8392-Object Oriented Programming
45
UNIT III EXCEPTION HANDLING AND I/O
Or
17.b.How we handle the exceptions?
There are two ways to handle Exceptions
Wrapping the desire code in a try block followed by a catch block to catch the exception
List the desired exception in the throws clause of the method and let the caller of the method handle
those exceptions.
18.a.What do you mean by chained exceptions?
Or
18.b.Define chained exceptions.
Chained Exceptions allows to relate one exception with another exception, i.e one excep-
tion describes cause of another exception.
Throwable methods that supports chained exceptions are:
1. getCause() method :- This method returns actual cause of an exception.
2. initCause(Throwable cause) method :- This method sets the cause for the calling
exception.
19.a.Write short notes on stacktraceElement.
Or
19.b.Define stacktrace element
The StackTraceElement class element represents a single stack frame which is a stack
trace when an exception occurs. Extracting stack trace from an exception could provide useful
information such as class name, method name, file name, and the source-code line number. This
creates a stack trace element representing the specified execution point.
getStackTrace( ) - returns an array of StackTraceElements.
20.a.List any three common run time errors.
Or
20.b.Write three common run time errors.
Exception Description
ArithmeticException Arithmetic error, such as divide-by-zero
ArrayIndexOutOfBoundsException Array index is out-of-bounds
IllegalThreadStateException Requested operation not compatible with
current thread state
21.a.Differentiate throw and throws in Java.
Or
21.b.State the differences for throw and throws
Thro throws
w
Java throw keyword is used to explicitly Java throws keyword is used to declare an
throw an exception. exception.
Checked exception cannot be propagated Checked exception can be propagated
using throw only. with throws.
Throw is followed by an instance. Throws is followed by class.
Throw is used within the method. Throws is used with the method signa-
CS8392-Object Oriented Programming
46
UNIT III EXCEPTION HANDLING AND I/O
ture.
You cannot throw multiple exceptions. You can declare multiple exceptions e.g.
public void method()throws IO Exception,
SQL Exception.
void m(){ void m() throws IOException{
//code
} }
22.a.Define Stream.
Or
22.b.What is Stream?
A stream can be defined as a sequence of data. The InputStream is used to read data from
a source and the OutputStream is used for writing data to a destination.
23.aList the type of streams supported in Java.
Or
23.b.What are the types of streams?
1.Byte Stream : It is used for handling input and output of 8 bit bytes. The frequently used classes
are FileInputStream and FileOutputStream.
2.Character Stream : It is used for handling input and output of characters. Charac-ter stream uses
16 bit Unicode. The frequently used classes are FileReader and File Writer.
24.a.List out the predefined streams available in Java.
Or
24.b.What are the built-In streams in Java.
ream which is the keyboard by default. This is used
system.out.
computer screen is used for standard error stream and represented as system.err.
25.a.What is Byte stream in Java? list some of the Bytestream classes.
Or
25.b.Define Byte stream.
The byte stream classes provide a rich environment for handling byte-oriented I/O. List of
Byte Stream classes
Byte Array Input Stream Byte Array Output Stream Filtered Byte Streams
26.a.What is character stream in Java? list some of the characterstream classes.
Or
26.b.Define character stream.
The Character Stream classes provide a rich environment for handling character-oriented I/O.
List of Character Stream classes
File Reader File Writer Char Array Reader Char Array Writer
CS8392-Object Oriented Programming
47
UNIT III EXCEPTION HANDLING AND I/O
27.a.What are the steps involved in stream i/o operations?
Or
27.b.Write the steps involved in stream I/O Operations.
1. Open an input/output stream associated with a physical device (e.g., file, network,
console/keyboard), by constructing an appropriate I/O stream instance.
2. -of-
opened output stream (and optionally flush the buffered output).
3. Close the input/output stream.
28.a.Write about read() method.
Or
28.b.Deine read() method.
Returns the input byte read as an int in the range of 0 to 255, or returns -
st throws an IOException if it encounters an I/O error.
The read() method returns an int instead of a byte, because it uses -1 to indicate end-of- stream.
The read() method blocks until a byte is available, an I/ -of-
detected.
29.a.What are the two variations of read() method?
Or
29.b.Define two variants of read( ) method.
public int read(byte[] bytes, int offset, int length) throws IOException public int
read(byte[] bytes) throws IOException
30.a.What are the two variations of write() method?
Or
30.b.Define the variants of write( ) method
public void write(byte[] bytes, int offset, int length) throws IOException public void
write(byte[] bytes) throws IOException
31.a
Or
31.b.State the differences for printf, print()and println.
print() - prints string inside the quotes
println() - prints string inside the quotes similar like print() method. Then the
cursor moves to the beginning of the next line.
printf() - it provides string formatting (similar to printf in C/C++ programming).
32.a.Write about Fileinputstream.
Or
32.b.Define File Inputstream
This stream is used for reading data from the files.
Objects can be created using the keyword new and there are several types of constructors available.
The two constructors which can be used to create a FileInputStream object:
i) Following constructor takes a file name as a string to create an input stream object to read
the file:
OutputStream f = new FileOutputStream("filename ");
ii) Following constructor takes a file object to create an input stream object to read the file.
First we create a file object using File() method as follows:
33.a.Write about Fileoutputstream.
Or
33.b.Define File Output stream.
FileOutputStream is used to create a file and write data into it.
CS8392-Object Oriented Programming
48
UNIT III EXCEPTION HANDLING AND I/O
constructors which can be used to create a FileOutputStream object:
i) Following constructor takes a file name as a string to create an input stream object to write
the file:
ii) Following constructor takes a file object to create an output stream object to write the file.
First, we create a file object using File() method as follows:
Fi
PART B
1.a.Draw the Hierarchy of Java Exception classes(6)
Or
1.b. Write about Exception Hierarchy in Java(6)
2.a.Explain the throwing and catching the exception in java(13)
Or
2.b.Discuss on exception handling in java.(13)
Or
2.c.Explain exception handling in java with examples.(13)
Or
2.d.Explain 5 keywords in exception handling in java with examples.(13)
Or
2.e.Explain with an example the exception handling feature in Java(13)
3.a.Draw the Internal working of java try-catch block(5)
Or
3.b. How the try-catch block works in Java?(5)
4.a.Explain Built-In Exceptions in Java with example programs.(13)
Or
4.b.What are the predefined exceptions in java with example programs?
5.a.Explain Creating Own Exception in java with examples(10)
Or
5.b.Expain about Custom Exception with example(10)
Or
5.c.Write about User-Defined exception with examples(10)
6.a.Discuss about the Java error handling mechanism? What is the difference bet -
CS8392-Object Oriented Programming