Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 36

1) What Is an Exception?

Ans:- An exception is an event, which occurs


during the execution of a program, that
interrupts the normal flow of the program's
instructions.

2) Why do we need Exceptions?


Ans:

Advantages of Exceptions

Advantage 1: Separating Error-Handling Code


from "Regular" Code

Exceptions provide the means to separate the


details of what to do when something out of the
ordinary happens from the main logic of a
program. In traditional programming, error
detection, reporting, and handling often lead to
confusing code. For example, consider the
pseudo code method here that reads an entire
file into memory.

readFile {
open the file;
allocate that much memory;
read the file into memory;
close the file;
}
At first glance, this function seems simple
enough, but it ignores all the following potential
errors.

What happens if the file can't be opened?


What happens if enough memory can't be
allocated?
What happens if the read fails?
What happens if the file can't be closed?

To handle such cases, the readFile function


must have more code to do error detection,
reporting, and handling. Here is an example of
what the function might look like.

errorCodeType readFile {
initialize errorCode = 0;

open the file;


if (theFileIsOpen) {
determine the length of the file;
if (gotEnoughMemory) {
read the file into memory;
if (readFailed) {
errorCode = -1;
}
} else {
errorCode = -2;
}
} else {
errorCode = -3;
}
close the file;
if (theFileDidntClose && errorCode == 0) {
errorCode = -4;
} else {
errorCode = errorCode and -4;
}
} else {
errorCode = -5;
}
return errorCode;
}
There's so much error detection, reporting, and
returning here that the original seven lines of
code are lost in the clutter. Worse yet, the logical
flow of the code has also been lost, thus making
it difficult to tell whether the code is doing the
right thing: Is the file really being closed if the
function fails to allocate enough memory? It's
even more difficult to ensure that the code
continues to do the right thing when you modify
the method three months after writing it. Many
programmers solve this problem by simply
ignoring it — errors are reported when their
programs crash.

Exceptions enable you to write the main flow of


your code and to deal with the exceptional cases
elsewhere. If the readFile function used
exceptions instead of traditional error-
management techniques, it would look more like
the following.

readFile {
try {
open the file;
determine its size;
allocate that much memory;
read the file into memory;
close the file;
} catch (fileOpenFailed) {
doSomething;
} catch (memoryAllocationFailed) {
doSomething;
} catch (readFailed) {
doSomething;
} catch (fileCloseFailed) {
doSomething;
}
}
Note that exceptions don't spare you the effort of
doing the work of detecting, reporting, and
handling errors, but they do help you organize
the work more effectively.

Advantage 2: Propagating Errors Up the Call


Stack

A second advantage of exceptions is the ability


to propagate error reporting up the call stack of
methods. Suppose that the readFile method is
the fourth method in a series of nested method
calls made by the main program: method1 calls
method2, which calls method3, which finally
calls readFile.

method1 {
call method2;
}

method2 {
call method3;
}

method3 {
call readFile;
}
Suppose also that method1 is the only method
interested in the errors that might occur within
readFile. Traditional error-notification techniques
force method2 and method3 to propagate the
error codes returned by readFile up the call
stack until the error codes finally reach method1
—the only method that is interested in them.

method1 {
errorCodeType error;
error = call method2;
if (error)
doErrorProcessing;
else
proceed;
}

errorCodeType method2 {
errorCodeType error;
error = call method3;
if (error)
return error;
else
proceed;
}

errorCodeType method3 {
errorCodeType error;
error = call readFile;
if (error)
return error;
else
proceed;
}

A method can duck any exceptions thrown


within it, thereby allowing a method farther up
the call stack to catch it. Hence, only the
methods that care about errors have to worry
about detecting errors.

method1 {
try {
call method2;
} catch (exception e) {
doErrorProcessing;
}
}

method2 throws exception {


call method3;
}

method3 throws exception {


call readFile;
}
However, as the pseudo code shows, ducking
an exception requires some effort on the part of
the middleman methods. Any checked
exceptions that can be thrown within a method
must be specified in its throws clause.

Advantage 3: Grouping and Differentiating Error


Types

Because all exceptions thrown within a program


are objects, the grouping or categorizing of
exceptions is a natural outcome of the class
hierarchy. An example of a group of related
exception classes in the Java platform are those
defined in java.io — IOException and its sub
classes. IOException is the most general and
represents any type of error that can occur when
performing I/O. Its sub classes represent more
specific errors. For example,
FileNotFoundException means that a file could
not be located on disk.

A method can write specific handlers that can


handle a very specific exception. The
FileNotFoundException class has no sub class,
so the following handler can handle only one
type of exception.
catch (FileNotFoundException e) {
...
}

A method can catch an exception based on its


group or general type by specifying any of the
exception's superclasses in the catch statement.
For example, to catch all I/O exceptions,
regardless of their specific type, an exception
handler specifies an IOException argument.

catch (IOException e) {
...
}

This handler will be able to catch all I/O


exceptions, including FileNotFoundException,
EOFException, and so on. You can find details
about what occurred by querying the argument
passed to the exception handler. For example,
use the following to print the stack trace.

catch (IOException e) {
// Output goes to System.err.
e.printStackTrace();
// Send trace to stdout.
e.printStackTrace(System.out);
}

You could even set up an exception handler that


handles any Exception with the handler here.

// A (too) general exception handler


catch (Exception e) {
...
}

3) Describe the exception hierarchy in java.


Ans:-
4) What is the difference between “Exception”
and “Error”?
Ans:-
Both Error and Exception are derived
from java.lang.Throwable. 
Examples of Error are:
java.lang.OutOfMemoryError or Java.lang.NoClassD
efFoundError 
java.lang.UnSupportedClassVersionError etc.
examples of Exception are:
java.lang.RuntimeException (unchecked) ,
java.io.IOException (checked) etc.
The first difference is Error is unchecked by nature
whereas Exceptions can be checked or unchecked.
The second difference is that Error is not meant
to catch as even if you catch it you cannot recover
from it. For example during OutOfMemoryError, if
you catch it you will get it again because GC may
not be able to free memory in first place. On the
other hand Exception can be caught and handled
properly.
i.e. Errors are fatal in nature and recovery may not
be possible, on the other hand by carefully handling
Exception you can make your code more robust and
guard against different scenarios.

An exception is an event that represents a condition


from which is possible to recover, whereas error
represents an external situation usually impossible
to recover from.
All errors thrown by the JVM are instances
of Error or one of its subclasses, the more common
ones include but are not limited to:
 OutOfMemoryError – thrown when the JVM
cannot allocate more objects because it is out
memory, and the garbage collector was unable
to make more available
 StackOverflowError – occurs when the stack
space for a thread has run out, typically because
an application recurses too deeply
 ExceptionInInitializerError – signals that an
unexpected exception occurred during the
evaluation of a static initializer. E.g.
public class MyClass
{
static MyClass m=null;
static
{
m.disp();
}
public void disp()
{
System.out.println("in disp");
}
public static void main(String[] args)
{
System.out.println("done");
}
}
Output: Exception in thread "main"
java.lang.ExceptionInInitializerError
Caused by: java.lang.NullPointerException
at
trial.MyClass.<clinit>(MyClass.java:8)
 NoClassDefFoundError – is thrown when the
classloader tries to load the definition of a class
and couldn’t find it, usually because
the required classfiles were not found in the
classpath
 UnsupportedClassVersionError – occurs when
the JVM attempts to read a classfile and
determines that the version in the file is not
supported, normally because the file was
generated with a newer version of Java
Although an error can be handled with
a try statement, this is not a recommended practice
since there is no guarantee that the program will be
able to do anything reliably after the error was
thrown.

5) What happens when an exception is raised in


a program?
Ans:- When an exception occurs within a method,
the method creates an object and hands it off to the
runtime system. The object, called an exception
object, contains information about the error,
including its type and the state of the program when
the error occurred. Creating an exception object and
handing it to the runtime system is called throwing
an exception.
After a method throws an exception, the runtime
system attempts to find something to handle it.
The set of possible "somethings" to handle the
exception is the ordered list of methods that had
been called to get to the method where the error
occurred. The list of methods is known as
the call stack .
The call stack

The runtime system searches the call stack for a


method that contains a block of code that can
handle the exception. This block of code is called
an exception handler. The search begins with the
method in which the error occurred and proceeds
through the call stack in the reverse order in which
the methods were called. When an appropriate
handler is found, the runtime system passes the
exception to the handler. An exception handler is
considered appropriate if the type of the exception
object thrown matches the type that can be handled
by the handler.
The exception handler chosen is said to catch the
exception. If the runtime system exhaustively
searches all the methods on the call stack without
finding an appropriate exception handler, the
program execution aborts.
6) Why do u handle the exception ?
Ans:- exception handling ensures normal program execution even
after exception gets raised.
7) How to handle the exception ?
Ans:- using try….catch block
8) When u write one try and multiple catch, what care u should
take?
Ans:- The most specific catch block should precede the most
generic catch block.

9) Can we write catch block in a following manner:


catch(Object ref)
{
}
Ans:- No we cannot write catch block that way. Only “Throwable”
class or one of its child classes can be the argument type in a catch clause. It
is because, if the catch block is allowed to write in this way, we
can use “throw new String()” or “throw new Thread()” etc.
All the above mentioned combinations are illegal because Objects
that are instances of “Throwable” class (or one of its child classes) only are
thrown by the JVM or can be thrown by the Java throw statement. 
10) What is finally block? Why do we need it?
Ans:- finally block is the one which gets executed irrespective of
whether exception is raised or not. Since it is guaranteed to be
invoked, we can release the resources such as file, database
connection, sockets etc. inside it.
5) in which scenarios finally block will not get executed?
Ans:- System.exit(0) in try or catch and any unhandled
exception is raised inside finally block.

6) Define checked and unchecked exception.


Ans :

 Checked exceptions:  Checked exceptions are


those exceptions which can be raised in a correct
program. Client code has to either handle the
checked exceptions or declare them with the throws
clause.
 Unchecked exceptions: Unchecked exceptions are
those exceptions which can be raised due to
programming mistakes. Unchecked exceptions
derived from RuntimeException. Exceptions that
inherit from RuntimeException get special
treatment. There is no requirement for the client
code to deal with them.
7) In java, adjectives ending in -able are interfaces Serializable,
Comparable , Cloneable etc... So why is Throwable a class and
not an interface?
Ans:- it is because they wanted to have some state associated
with every exception that gets thrown such as message, cause,
and stack trace etc. and you can't do that with interfaces.
8) When will you create a checked exception?
Ans:- when you realize that client code will take some
useful recovery action based on information in exception
You can go for checked exception.

9) How do u create checked and unchecked exception?


Ans:- we create checked exceptions by deriving from “Exception”
class whereas we create unchecked exceptions by deriving from
“RuntimeException” class.

10) Compiler enforces u to deal with checked exception. What


do u mean by this?
Ans:- u must either handle ( using try… catch) or declare (using
throws)

11) Difference bet’n throw and throws.


Ans:- throw is used to raise the exception whereas throws is used
to declare the exception.

12) What is ARM block?


Ans:- ARM (Automatic Resource Management) block is also
known as “try with resource” block.
e..g try(FileInputStream fis=new FileInputStream())
{
Some statements….
}
catch(FileNotFoundException fe)
{
fe.printStackTrace();
}

The try-with-resources statement is a try statement


that declares one or more resources. A resource is
an object that must be closed after the program is
finished with it. The try-with-resources statement
ensures that each resource is closed at the end of
the statement. Any object that implements 
java.io.Closeable, can be used as a resource.

13) Is it recommended to handle


“NullPointerException”,”ClassCastExcepti
on” etc. using java code?
Ans:- No not at all. Exceptions are costly, and
can slow down your code. Don’t just throw and
catch exceptions, if you can use if..else
expression to indicate result of operation, e.g.
NullPointerException, ClassCastException etc.
which may result in cleaner code and
performance solution.
14) What is Re-throwing an exception in
java?
Ans:- Exceptions raised in the try block are
handled in the catch block. If it is unable to
handle that exception, it can re-throw that
exception using throw keyword. It is called re-
throwing an exception.

try
{
String s = null;
System.out.println(s.length()); //This
statement throws NullPointerException
}
catch(NullPointerException ex)
{
System.out.println("NullPointerException is
caught here");

throw ex; //Re-throwing


NullPointerException
}
15) What are the legal combinations of try,
catch and finally blocks?
Ans:-
A)
try
{
//try block
}
catch(Exception ex)
{
//catch block
}

B)

try
{
//try block
}
finally
{
//finally block
}
C)

try
{
//try block
}
catch(Exception ex)
{
//catch block
}
finally
{
//finally block
}

16)What are some of the best practices of


Exception Handling?
Ans:-
a. When deciding on checked exceptions vs. unchecked
exceptions, ask yourself, "What action can the client code
take when the exception occurs?"

If the client can take some alternate action to recover from the
exception, make it a checked exception. If the client cannot do
anything useful, then make the exception unchecked. By useful, it
means, taking steps to recover from the exception and not just logging the exception. To
summarize:

Client's reaction when exception


Exception type
happens
Make it an
Client code cannot do anything
unchecked exception
Client code will take some useful recovery Make it a checked
action based on information in exception exception

Moreover, prefer unchecked exceptions for all programming


errors: unchecked exceptions have the benefit of not forcing the
client API to explicitly deal with them. They propagate to where
you want to catch them, or they go all the way out and get
reported. The Java API has many unchecked exceptions, such
as NullPointerException, IllegalArgumentException,
andIllegalStateException.

b. Preserve encapsulation.

Never let implementation-specific checked exceptions rise to the


higher layers. For example, do not propagate SQLException from
data access code to the business objects layer. Business objects
layer do not need to know about SQLException. You have two
options:

 Convert SQLException into another checked exception, if


the client code is expected to recover from the exception.
 Convert SQLException into an unchecked exception, if the
client code cannot do anything about it.

Most of the time, client code cannot do anything


about SQLExceptions. Do not hesitate to convert them into
unchecked exceptions. Consider the following piece of code:

public void dataAccessCode(){


try{
..some code that throws SQLException
}catch(SQLException ex){
ex.printStacktrace();
}
}

This catch block just suppresses the exception and does nothing.


The justification is that there is nothing my client could do about
an SQLException. How about dealing with it in the following
manner?

public void dataAccessCode(){


try{
..some code that throws SQLException
}catch(SQLException ex){
throw new RuntimeException(ex);
}
}

This converts SQLException to RuntimeException.
If SQLException occurs, the catch clause throws a new
RuntimeException. The execution thread is suspended and the
exception gets reported. Here we are not corrupting our business
object layer with unnecessary exception handling, especially since
it cannot do anything about an SQLException. If
our catch needs the root exception cause, we can make use of
the getCause() method available in all exception classes as of
JDK1.4.

c) Close or release resource in finally block


This is a well-known best practice in Java and quite
a standard, while dealing with networking and IO
classes. Closing resources in finally block
guarantees that precious and scarce resource
released properly in case of normal and aborted
execution, guaranteed by finally block. From Java 7,
language has a more interesting automatic resource
management or ARM blocks, which can do this for
you. Nevertheless, always remember to close
resources in finally block, which is important to
release limited resources like FileDescriptors,
used in case of both socket and files.

d) Including cause of Exception in stack-trace


Many times Java library and open source code
wraps one Exception into another, when one
exception is thrown due to result of another
exception. Its become extremely important to log or
print cause of root exception. Java Exception class
provides getCause() method to retrieve cause
which can be used to provide more information
about root cause of Exception. This Java best
practice helps a lot while debugging or
troubleshooting an issue.

e) Always provide meaningfull message on


Exception
message of Exception is the most important place,
where you can point out cause of problem because
this is the first place every programmer looks upon.
Always try to provide precise and factual information
here. For example, compare these two Exception
messages for IllegalArgumentException :

message 1: "Incorrect argument for


method"
message 2: "Illegal value for $
{argument}: ${value}

first one just says that argument is illegal or


incorrect, but second one include both name of
argument and its illegal value which is important to
point out cause of error. Always follow this Java best
practice, when writing code for handling exceptions
and errors in Java.

f) Converting Checked Exception into


RuntimeException
This is one of the technique used to limit use of
checked Exception in many of frameworks like
Spring ,where most of checked Exception, which are
raised from JDBC is wrapped into
DataAccessException, an unchecked
Exception. This Java best practice provides benefits,
in terms of restricting specific exception into specific
modules, like SQLException into DAO layer and
throwing meaningful RuntimeException to client
layer.

g) Remember Exceptions are costly in terms of


performance
One thing which is worth remembering is that
Exceptions are costly, and can slow down your
code. Don’t just throw and catch exceptions, if you
can use boolean expression to indicate result of
operation, e.g. NullPointerException,
ClassCastException etc. which may result in cleaner
and performance solution.

h) Avoid empty catch blocks


Nothing is worse than empty catch block, because
it not just hides the Errors and Exception, but also
may leave your object in unusable or corrupt state.
Empty catch block only make sense, if you
absolutely sure that Exception is not going to affect
object state on any ways, but still it’s better to log
any error comes during program execution. This is
not a Java best practice, but a most common
practice, while writing Exception handling code in
Java.
i) Use Standard Exceptions
Our ninth Java best practice
advice on using standard and inbuilt Java
Exceptions. Using standard Exception instead of
creating own Exception every now and then is much
better in terms of maintenance and consistency.
Reusing standard exception makes code more
readable, because most of Java developers are
familiar with standard RuntimeException from
JDK like, IllegalStateException,
IllegalArgumentException etc. and they will
immediately be able to know purpose of Exception,
instead of looking out another place on code or docs
to find out purpose of user defined Exceptions.

j) Document Exception thrown by any method


Java provides throw and throws keyword to throw
exception and in javadoc you have @throw to
document possible Exception thrown by any
method. This becomes increasingly important if you
are writing API or public interface. With proper
documentation of Exception thrown by any method
you can potentially alert anyone who is using it.
Q. 14) what is the difference between
NoClassDefFoundError and
ClassNotFoundException?

Ans:-

15) What are the performance implications about


exception handling?

Ans:- Exceptions come with a price, and in order to


understand some of the issues involved, let's look at
the mechanism for handling exceptions. The Java
Virtual Machine maintains a method-invocation
stack (or call stack) that features a list of the
methods that have been invoked by a thread, starting
with the first method the thread invoked and ending
with the current method. A method-invocation stack
illustrates the path of method invocations a thread
made to arrive at the current method.

Figure 1. The Java method-invocation stack


shows frames for the methods invoked.

Figure 1 shows a graphical representation of the


method-invocation stack for our code. Inside the
Java Virtual Machine, methods keep their state
within the Java stack. Each method obtains a stack
frame, which pushes onto the stack when the method
invokes and pops from the stack when the method
completes. (The stack frame stores the method's
local variables, parameters, return value, and other
key information needed by the Java VM). As
methods continue to complete normally, their frames
pop and the stack frame below turns into the
currently executed method.
So, for the purposes of our comparison, what needs
to happen in Case 1? If a
NoPassengerFoundException throws while
executing the
searchPassengerFlightRecord() method
(the top stack frame), further execution of code halts
and the Java VM receives control to implement
Java's exception-handling mechanism. The Java VM
then searches in the current method for a catch
clause having NoPassengerFoundException.
If it doesn't find such a clause, then the Java VM
pops the stack frame for the current method, and the
calling method becomes the current method. The
Java VM again searches in the current method -- for
a suitable catch clause. If the Java VM still doesn't
find a suitable catch clause, it pops the current stack
frame and then searches the next stack frame for a
suitable catch clause, and so on, until it finally finds
an appropriate one. Or, if it doesn’t find, then the
application terminates with the stack trace printing
on the console. Abrupt method completion is
significantly more expensive (performance-wise)
than a normal method completion.
17) What are Chained Exceptions in Java?
Ans:- Chained Exceptions allows to relate one
exception with another exception, i.e one exception
describes cause of another exception. For example,
consider a situation in which a method throws an
ArithmeticException because of an attempt to divide
by zero but the actual cause of exception was an I/O
error which caused the divisor to be zero. The
method will throw only ArithmeticException to the
caller. So the caller would not come to know about
the actual cause of exception. Chained Exception is
used in such type of situations.

Constructors Of Throwable class Which support


chained exceptions in java :
1. Throwable(Throwable cause) :- Where cause is
the exception that causes the current exception.
2. Throwable(String msg, Throwable cause) :-
Where msg is the exception message and cause is
the exception that causes the current exception.
Methods Of Throwable class Which support chained
exceptions in java :
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.
Example of using Chained Exception:

// Java program to demonstrate working of chained


exceptions
public class ExceptionHandling
{
    public static void main(String[] args)
    {
        try
        {
            // Creating an exception
            NumberFormatException ex =
                       new
NumberFormatException("Exception");
 
            // Setting a cause of the exception
            ex.initCause(new NullPointerException(
                      "This is actual cause of the exception"));
 
            // Throwing an exception with cause.
            throw ex;
        }
 
        catch(NumberFormatException ex)
        {
            // displaying the exception
            System.out.println(ex);
 
            // Getting the actual cause of the exception
            System.out.println(ex.getCause());
        }
    }
}
Run on IDE
Output:
java.lang.NumberFormatException: Exception
java.lang.NullPointerException: This is actual cause
of the exception

18) How do you convert checked exception to


unchecked exception?
Ans:-
Your code:
try
{
Some statements
…………
}
catch(CheckedException ce)
{
throw new UncheckedException();
}

Now your caller need not handle or declare exception


because you have converted checked exception to
unchecked exception.

You might also like