0% found this document useful (0 votes)
3 views

,assignment -1[1]

Assignment

Uploaded by

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

,assignment -1[1]

Assignment

Uploaded by

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

Assignment: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

 These exceptions occur at runtime.


 The compiler doesn’t check for these kinds of exceptions.
 These kinds of exceptions can’t be caught or handled during
compilation time.
 This is because the exceptions are generated due to the mistakes in
the program.
 These are not a part of the ‘Exception’ class since they are runtime
exceptions.
 The JVM doesn’t require the exception to be caught and handled.
 Example of Unchecked Exceptions- ‘No Such Element Exception’.

2. What is the difference between finally, final, and finalize in Java?

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.

4. Define Runtime Exception. Describe it with the help of an example.


RuntimeExceptions are those exceptions which are checked at runtime.
RuntimeException is the superclass of all those exceptions that can be thrown
during the normal execution of the Java program. These are also called as
unchecked exceptions. RuntimeException and their subclasses are known as
unchecked exceptions. RuntimeExceptions can be avoided by programmer.

Examples – ArithmeticException, ArrayStoreException, CannotRedoException,


CannotUndoException, ClassCastException, CMMException,
ConcurrentModificationException, EmptyStackException,
IllegalArgumentException, IllegalMonitorStateException,
IllegalPathStateException, IllegalStateException, ImageFormatException,
ImagingOpException, IndexOutOfBoundsException, MissingResourceException,
NegativeArraySizeException, NoSuchElementException, NullPointerException,
ProfileDataException, ProviderException, RasterFormatException,
SecurityException, SystemException, TruncatedFileException,
UnsupportedOperationException etc.
5. What is the difference between NoClassDefFoundError and
ClassNotFoundException in Java?

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

present in the classpath. time

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()

6. Can we throw an exception explicitly or manually?


An exception can be thrown explicitly, when a condition is met. In other words,
in a situation where an exception is predicted by the developers, then it can be
explicitly thrown. The key word ‘throw’ is used followed by the object of the
exception and it accepts only one parameter.

7. Describe the use of the throw keyword.

The Java throw keyword is used to throw an exception explicitly.

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 throw either checked or unchecked exceptions in Java by throw


keyword. It is mainly used to throw a custom exception. We will discuss custom
exceptions later in this section.

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.

The syntax of the Java throw keyword is given below.


throw Instance is - throw new exception_class("error message");

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.

9. Describe OutofMemoryError in exception handling.

OutOfMemoryError usually means that you’re doing something wrong, either


holding onto objects too long or trying to process too much data at a time.
Sometimes, it indicates a problem that’s out of your control, such as a third-
party library that caches strings or an application server that doesn’t clean up
after deploys. And sometimes, it has nothing to do with objects on the heap. The
java.lang.OutOfMemoryError exception can also be thrown by native library
code when a native allocation cannot be satisfied (for example, if swap space is
low). Let us understand various cases when the OutOfMemory error might
occur.

10. Is there any difference between throw and throws in exception handling in
Java?

Parameters Throw in Java Throws in Java

Definition The throw keyword helps in We use the throws keyword


throwing an exception in the in the method signature. We
program, explicitly inside some use it to declare some
block of code or inside any exceptions thrown by a
function. function when the code is
getting executed.

Internal The throw keyword is With the throws keyword,


Implementation implemented internally because it on the other hand, one can
is only allowed to throw a single easily declare various
exception at once. It means that it exceptions. These could be
is not possible to throw multiple thrown by any function
exceptions when we are using the when using the throws
throw keyword. keyword.

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).

11. Provide me with some examples of unchecked exceptions.


Checked Exception Example
Unchecked Exception Example

12. Is it illegal to keep an empty catch?

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:

 Inform the user about the exception.


 Log the exception for debugging purposes and future reference.
 Send an email describing the exception.

It all depends on the issue and workflow what to do if an exceptions occurs.


catch block can be used to rethrow the exceptions as well. If we choose to keep
catch block empty then it means we decided to do nothing.

If you deliberately decide to keep empty catch block, put at least a comment
why you decided to do so.

13. Can checked exceptions occur at compiled time?

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.

14. What happens if a runtime exception occurs?


The Runtime Exception is the parent class in all exceptions of the Java
programming language that are expected to crash or break down the program
or application when they occur. Unlike exceptions that are not considered as
Runtime Exceptions, Runtime Exceptions are never checked.
The Runtime Exception usually shows the programmer's error, rather than the
condition a program is expected to deal with. Runtime Exceptions are also used
when a condition that can't happen. It should be noted that when a program is
running out of memory, a program error is thrown instead of showing it as a
Runtime Exception.

15. Describe unreachable catch block error in Java.


A block of statements to which the control can never reach under any case
can be called as unreachable blocks. Unreachable blocks are not supported
by Java. The catch block mentioned with the reference of Exception class
should and must be always last catch block because Exception is
the superclass of all exceptions. When we are keeping multiple catch blocks,
the order of catch blocks must be from most specific to most general
ones. i.e subclasses of Exception must come first and superclasses later. If we
keep superclasses first and subclasses later, the compiler will throw an
unreachable catch block error.

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.

17. Define user-defined or custom exceptions in Java.


Java Custom Exception

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.

Why use custom exceptions?

Java exceptions cover almost all the general type of exceptions that may occur
in the programming. However, we sometimes need to create custom exceptions.

Following are few of the reasons to use custom exceptions:

o To catch and provide specific treatment to a subset of existing Java


exceptions.
o Business logic exceptions: These are the exceptions related to business
logic and workflow. It is useful for the application users or the developers
to understand the exact problem.

In order to create custom exception, we need to extend Exception class that


belongs to java.lang package.

18. What do you understand by a chained exception?

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 : Throwable(Throwable cause) :-
Where cause is the exception that causes the current exception.
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 :

getCause() method :- This method returns actual cause of an exception.

initCause(Throwable cause) method :- This method sets the cause for the calling
exception.

19. What do you understand about throwables in Java?

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.

For the purposes of compile-time checking of exceptions, Throwable and any


subclass of Throwable that is not also a subclass of either RuntimeException or
Error are regarded as checked exceptions.

Instances of two subclasses, Error and Exception, are conventionally used to


indicate that exceptional situations have occurred.

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.

Throwing a "wrapped exception" (i.e., an exception containing a cause) allows


the upper layer to communicate the details of the failure to its caller without
incurring either of these shortcomings. It preserves the flexibility to change the
implementation of the upper layer without changing its API (in particular, the
set of exceptions thrown by its methods). A second reason that a throwable may
have a cause is that the method that throws it must conform to a general-
purpose interface that does not permit the method to throw the cause directly.
For example, suppose a persistent collection conforms to the Collection
interface, and that its persistence is implemented atop java.io. Suppose the
internals of the add method can throw an IOException. The implementation can
communicate the details of the IOException to its caller while conforming to the
Collection interface by wrapping the IOException in an appropriate unchecked
exception. (The specification for the persistent collection should indicate that it
is capable of throwing such exceptions.)

20. Mention the methods in the throwable class.

Java Throwable class provides several methods like addSuppressed(),


fillInStackTrace(), getMessage(), getStackTrace(), getSuppressed(), toString(),
printStackTrace() etc. Method getMessage() getSuppressed() getStackTrace()
fillInStackTrace() getLocalizedMessage() initCause() getCause()
printStackTrace()

21. Give me some examples of checked exceptions.


22. Define NumberFormatException exception in Java.

The NumberFormatException is an unchecked exception in Java that occurs


when an attempt is made to convert a string with an incorrect format to a
numeric value. Therefore, this exception is thrown when it is not possible to
convert a string to a numeric type (e.g. int, float). For example, this exception
occurs if a string is attempted to be parsed to an integer but the string contains
a boolean value.
Since the NumberFormatException is an unchecked exception, it does not need
to be declared in the throws clause of a method or constructor. It can be
handled in code using a try-catch block.

23. What do you understand by ArrayIndexOutOfBoundsException?


The ArrayIndexOutOfBoundsException is a runtime exception in Java that
occurs when an array is accessed with an illegal index. The index is either
negative or greater than or equal to the size of the array.
Since the ArrayIndexOutOfBoundsException is an unchecked exception, it does
not need to be declared in the throws clause of a method or constructor.

What Causes ArrayIndexOutOfBoundsException

The ArrayIndexOutOfBoundsException is one of the most common errors in


Java. It occurs when a program attempts to access an invalid index in an array
i.e. an index that is less than 0, or equal to or greater than the length of the
array.

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.

d. After complete execution of catch block, statement 5 will be executed


normally. Thus, the control flow will be like this:
statement 1 ➞ statement 4 ➞ statement 5 ➞ Normal Termination.
Case 3:
Suppose an exception occurred at statement 2 and exception object created is
not matched with argument of the catch block. In this case, what will be the
control flow?
a. Statement 1 will be executed normally within try block.
b. If an exception occurred in statement 2 and the exception object created does
not match with argument of catch block, program will be terminated abnormally
and the rest of code will not execute.
For example, suppose an exception object is created for ArithmeticException
class and catch block has a reference of NullPointerException exception object
as an argument, in this case, both are not matched and program will be
terminated abnormally. So, the control flow will be like this:
statement 1 ➞ Abnormal Termination.
Case 4:
Suppose an exception occurred in statement 4 inside the catch block. In this
case, what will be control flow?
Note that an exception occurs not only inside try block but also can occur inside
catch and finally block. Since the exception has occurred in statement 4 inside
catch block and statement 4 is not inside the try block, the program will be
terminated normally.
Thus, control flow is like this:
statement 1 ➞ statement 2 ➞ statement 3 ➞ statement 5 ➞ Normal Termination.
If an exception occurs in any statement and statement is not inside the try block
then program will be terminated abnormally.
Case 5:
Suppose an exception occurs in statement 5. In this case, what will be control
flow?
Since statement 5 is not inside try block, program will be terminated
abnormally. The control flow will be as follows:
statement 1 ➞ statement 2 ➞ statement 3 ➞ Abnormal Termination.

25. Define unreachable catch block error.

An unreachable catch clause may indicate a logical mistake in the exception


handling code or may simply be unnecessary.

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:

 A checked exception that is thrown in the try block is assignable to the


parameter of C.
 There is no previous catch clause whose parameter type is equal to, or a
supertype of, the parameter type of C. However, a catch clause that is
considered reachable by the compiler can be unreachable if both of the
following conditions are true:
 The catch clause’s parameter type E does not include any unchecked
exceptions.
 All exceptions that are thrown in the try block whose type is a (strict)
subtype of E are already handled by previous catch clauses.

You might also like