,assignment -1[1]
,assignment -1[1]
Q1. Describe the difference between unchecked and checked exceptions in Java.
Ans- CHECKED EXCEPTION
They occur at compile time.
The compiler checks for a checked exception.
These exceptions can be handled at the compilation time.
It is a sub-class of the exception class.
The JVM requires that the exception be caught and handled.
Example of Checked exception- ‘File Not Found Exception’
UNCHECKED EXCEPTION
Final
It is a keyword.
It is used to apply restrictions on classes, methods and variables.
It can’t be inherited.
It can’t be overridden.
Final methods can’t be inherited by any class.
It is needed to initialize the final variable when it is being declared.
Its value, once declared, can’t be changed or re-initialized.
Finally
It is a block.
It is used to place important code in this block.
It gets executed irrespective of whether the exception is handled or
not.
Finalize
It is a method.
It is used to perform clean up processing right before the object is
collected by garbage collector.
3. Define try-with resource. How can you say that it differs from an ordinary
try?
Ans-In Java, the Try-with-resources statement is a try statement that declares
one or more resources in it. A resource is an object that must be closed once
your program is done using it. For example, a File resource or a Socket
connection resource. The try-with-resources statement ensures that each
resource is closed at the end of the statement execution. If we don’t close the
resources, it may constitute a resource leak and also the program could exhaust
the resources available to it. You can pass any object as a resource that
implements java.lang.AutoCloseable, which includes all objects which
implement java.io.Closeable.
CLASSNOTFOUNDEXCEPTION NOCLASSDEFFOUNDERROR
NoClassDefFoundError is
ClassNotFoundException is
an Error it
a checked Exception it
extends java.lang.LinkageError clas
extends java.lang.Exception class
s
ClassNotFoundException occurs NoClassDefFoundError occurs
when the application tries to load a when the class is found during
class dynamically which is not the compile time but not at the run
ClassNotFoundException occurs
NoClassDefFoundError occurs as a
by the explicit loading of the class
result of implicit loading of class
through Class.forName() or
due to a method call or while
ClassLoader.loadClass() or
accessing a other class variable
ClassLoader.findSystemClass()
We specify the exception object which is to be thrown. The Exception has some
message with it that provides the error description. These exceptions may be
related to user inputs, server, etc.
We can also define our own set of conditions and throw an exception explicitly
using throw keyword. For example, we can throw ArithmeticException if we
divide a number by another number. Here, we just need to set the condition and
throw exception using throw keyword.
8. Why should we clean up activities such as I/O resources in the finally block?
Catch block gets called only when an exception occurs or is explicitly thrown
but we need to release our resources in either case (task failure or success).
Finally block gets called irrespective of what happens in try. For example: we
fetch data from database. In this case the first step would be creating a
connection in order to access the database. Once our work is done successfully
or if our logic crashes we need to end the connection so we write it in a finally
block.
10. Is there any difference between throw and throws in exception handling in
Java?
Type of One can only propagate the When we use the throws
Exception unchecked exceptions using the keyword, we can declare
throw keyword. It means that no both unchecked and
checked exception can be checked exceptions. The
propagated when we use the checked expression must
throw keyword. always use the throws
keyword for propagation
followed by a specific name
of the exception class.
Syntax The instance variable follows the The exception class names
throw keyword. follow the throws keyword.
Declaration When we are using the throw The throws keyword, on the
keyword, we must ensure that we other hand, must always be
are using the throw keyword used within the signature of
within the available method. a method (method
signature).
It is legal to have an empty catch block. If we have empty catch block then
nothing happens. Empty catch block is something like silently ignoring the
exception without doing anything and informing anyone. Which is a bad idea.
Generally we do the following in catch blocks:
If you deliberately decide to keep empty catch block, put at least a comment
why you decided to do so.
Checked exceptions are checked at compile time to ensure you are handling
them, either by catching them or declaring the containing method throws the
exception.
At runtime, there is no distinction between checked and unchecked exceptions:
they are treated identically by the JVM. So "checked-ness" is purely a compile-
time concept.
Syntax
try {
// statements
} catch(Exception e) {
System.out.println(e);
} catch(NumberFormatException nfe) { //unreachable block. Not supported
by Java, leads to an error.
System.out.println(nfe);
}
16. In which situation will you not be able to execute the finally block?
In Java, there is one possibility where finally block will not be executed. They
are as follows:
When the System.exit() method is called in the try block before the execution of
finally block, finally block will not be executed.
In Java, we can create our own exceptions that are derived classes of the
Exception class. Creating our own Exception is known as custom exception or
user-defined exception. Basically, Java custom exceptions are used to customize
the exception according to user need.
Using the custom exception, we can have your own exception and message.
Here, we have passed a string to the constructor of superclass i.e. Exception
class that can be obtained using getMessage() method on the object we have
created.
Java exceptions cover almost all the general type of exceptions that may occur
in the programming. However, we sometimes need to create custom exceptions.
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.
initCause(Throwable cause) method :- This method sets the cause for the calling
exception.
The Throwable class is the superclass of all errors and exceptions in the Java
language. Only objects that are instances of this class (or one of its subclasses)
are thrown by the Java Virtual Machine or can be thrown by the Java throw
statement. Similarly, only this class or one of its subclasses can be the
argument type in a catch clause.
Typically, these instances are freshly created in the context of the exceptional
situation so as to include relevant information (such as stack trace data). A
throwable 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. Over time, a throwable can suppress other throwables from being
propagated. Finally, the throwable can also contain a cause: another throwable
that caused this throwable to be constructed. The recording of this causal
information is referred to as the chained exception facility, as the cause can,
itself, have a cause, and so on, leading to a "chain" of exceptions, each caused
by another.
One reason that a throwable may have a cause is that the class that throws it is
built atop a lower layered abstraction, and an operation on the upper layer fails
due to a failure in the lower layer. It would be bad design to let the throwable
thrown by the lower layer propagate outward, as it is generally unrelated to the
abstraction provided by the upper layer. Further, doing so would tie the API of
the upper layer to the details of its implementation, assuming the lower layer's
exception was a checked exception.
Since a Java array has a range of [0, array length - 1], when an attempt is made
to access an index outside this range, an ArrayIndexOutOfBoundsException is
thrown.
24. Suppose there is a catch block in tune with a try block with 3 statements - 1,
2, and 3. Now, imagine that the statement is thrown in statement 2. Will there
be an execution of statement 3?
In the above code, there are three statements inside try block, one statement
block inside catch block, and one statement outside try-catch block. Let’s see
different cases.
Case 1:
Suppose no exception occurs inside try block then statement 1, statement 2,
and statement 3 will be executed normally. But, the catch block will not be
executed because no exception is thrown by try block.
After complete execution of try block, the control of execution will be passed to
the next statement. Now, statement 5 will execute normally. Thus, the control
flow will be like this:
statement 1 ➞ statement 2 ➞ statement 3 ➞ statement 5 ➞ Normal Termination
of program.
If no exception occurs within try block, Except catch block, all remaining code
will be executed normally.
Case 2:
Suppose an exception occurs in statement 2 inside try block and the exception
object created inside try block is matched with argument of catch block. What
will be the control flow in this case?
a. Inside try block, statement 1 will be executed normally.
b. When the exception occurred in statement 2, the control of execution
immediately is transferred to catch block and statement 4 inside the catch block
will be executed.
c. After executing statement 4, statement 3 in try block will not be executed
because the control never goes back to execute remaining code inside try block.
Although certain unreachable catch clauses cause a compiler error, there are
also unreachable catch clauses that do not cause a compiler error.
A catch clause C is considered reachable by the compiler if both of the following
conditions are true: