Java Exception in T
Java Exception in T
Questions
© Copyright by Interviewbit
Contents
Introduction
An Exception refers to abnormal behaviour of an application that occurs at the time
of execution that could lead to the termination of that application if not handled.
Exceptions could include sudden network errors, database connection errors, errors
due to non-existent or corrupt files, logical errors that were not handled by the
developers and many more. Java provides a great way of handling Exceptions that
results in a robust application that does not fail in case of abnormalities. Due to its
importance, exception handling has become a very important and favourite topic
amongst interviewers. Every so ware developer should know how to handle
unexpected errors while developing an application.
In this article, we will go through the commonly asked Exception-Handling Interview
Questions for both freshers and experienced so ware developers:
Exception Handling Interview Questions for Freshers
Exception Handling Interview Questions for Experienced
MCQ Questions on Exception Handling in Java
The following are some of the Advantages of using Exception Handling in Java:
Case 2: Return the score as 0 and log the error that file doesn’t exist as shown in
the logic below.
Finally, irrespective of whether the code running normally or not, we would want to
close the resources. This could run in the finally block as shown below:
Note:
As of Java 7, the new feature “try-with-resources” helps to autoclose the
resources that extend the “AutoCloseable” interface. The close() method will be
called when it exits the try-with-resources block. For example, the above code
which has a close() method call could be simplified as shown below:
Sometimes, the program could throw more than 1 exception. In this case, Java
supports the usage of multiple catch blocks. Our example could also encounter
a NumberFormatException exception while parsing integer numbers and this
could be handled as shown below:
Multiple catch blocks are useful if we have different exception-handling logic for
different types of exceptions. If our logic of handling the exception is the same
(as in the above scenario), then Java7 introduced the feature to union the catch
blocks - handle multiple exceptions in the same catch block. The above could
now be simplified to:
if (task.getStatus().equals("outdated")) {
throw new OutdatedTaskException("Task is outdated");
}
The throws keyword in Java is used along with the method signature to specify
exceptions that the method could throw during execution. For example, a method
could throw NullPointerException or FileNotFoundException and we can specify
that in the method signature as shown below:
Checked Exceptions
require handling using a
try-catch block or at
least the method should Unchecked Exceptions do not
use the throws require try-catch or throws
keyword to let the handling. These exceptions could
calling method know occur due to mistakes in
that a checked programming logic.
exception could be
thrown from this
method.
Examples: IOException,
Examples: ArithmeticException,
FileNotFoundException,
ArrayIndexOutOfBoundException,
DataAccessException,
NullPointerException,
InterruptedException,
InvalidClassException, etc.
etc.
try {
// do something
} catch (Exception exception) {
// handle exception
}
try {
// do something
} catch (FileNotFoundException fileNotFoundException) {
// handle FileNotFoundException
} catch (EOFException eofException) {
// handle EOFException
}
When we are using multiple catch blocks, we need to ensure that in a case where the
exceptions have an inheritance relationship, the child exception type should be the
first and the parent type later to avoid a compilation error.
Java 7 also began to provide the usage of multi-catch blocks for reducing
duplication of code if the exception handling logic was similar for different
exception types. The syntax of the multi-catch block is as shown below-
try {
// ...
} catch (FileNotFoundException | EOFException exception) {
// ...
}
To determine where an exception has occurred, we need to check for the beginning
of the trace that has a list of “at …”. In the given example, the exception has occurred
at Line Number 26 of the Book.java class in the getBookTitle() method. We can
look at this stack trace and go to the method and the line number mentioned in the
trace and debug for what could have caused the NullPointerException. Furthermore,
we can get to know that the getBookTitle() method in the Book.java class was
called by the getBookTitlesOfAuthor() method in the Author.java class in Line
Number 15 of the file and this in turn was called by the main() method of the
DemoClass.java file in Line Number 14.
14. How are the keywords final, finally and finalize different
from each other?
final keyword: By using this keyword,
we can declare a variable as final (meaning, variable value cannot be
changed).
we can declare a method as final (meaning, that method cannot be
overridden).
we can declare a class as final (meaning, that class cannot be extended).
finally keyword: This is used in conjunction with the try-catch block or the try
block where we want to run some logic whether or not an exception has
occurred.
finalize keyword: This is a method called by the Garbage Collector just before
destroying the objects no longer needed in the program.
When the expression is evaluated, the denominator becomes zero. Hence Java would
throw ArithmeticException when it’s executed. The exception logs would be:
We cannot throw a check exception from a static block. However, we can have try-
catch logic that handles the exception within the scope of that static block without
rethrowing the exception using the throw keyword. The exceptions cannot be
propagated from static blocks because static blocks are invoked at the compiled
time only once and no method invokes these blocks.
When there are exceptions that are to be thrown by the application, but the type is
not represented by any of the existing Exception types in Java, then we can provide
more detailed information by creating a custom exception. The creation of custom
exceptions depends on the business logic. While creating a custom exception, it is
recommended to inherit from the most specific Exception class that relates to the
exception we want to throw. If there are no such classes available, then we can
choose the Exception class as the parent for this new custom exception. Consider an
example -
We want to access a file and return the first line of the file content.
In the above case, when there is an exception while reading the file - we do not know
if it was caused due to absence of the file or if the name of the file provided was
wrong. To narrow this down, we will create a custom exception called
InvalidFileNameException by extending the Exception class as shown below:
To create a custom exception, we should also provide a constructor that makes a call
to the parent class constructor by using the super keyword. Our custom exception is
ready. The code logic now becomes:
import java.io.IOException;
import java.io.FileNotFoundException;
import javax.xml.bind.JAXBException;
}
}
26. Does the finally block always get executed in the Java
program?
The finally blocks are meant to be executed whenever there is an exception or not in
the try-catch blocks. However, there is one scenario where this block does not get
executed. It is when we use System.exit(0) in either try or catch block. This is
because the System.exit(0) terminates the running JVM.
28. Are we allowed to use only try blocks without a catch and
finally blocks?
Before Java 7, we were not allowed to use only try blocks. The try block should have
been followed by a catch or a finally block. But from Java 7 onwards, we can simply
have a try block with a catch or finally blocks in the form of try-with-resources that
takes parameters implementing the AutoCloseable interface. Note that, if the
parameters do not implement the AutoCloseable interface, then it leads to an
error.
foobar();
}
}
}
The program compiles successfully and it runs and displays nothing as no logic in
both methods could result in an exception.
If there are any exceptions in the demoMethod() , we can always catch the exception
and handle it. If the method foobar() declares NullPointerException using
throws clause, the method doesn’t need to throw an exception. However, if there is a
logic that results in performing operations on null objects inside the foobar()
method, then NullPointerException will be thrown by the method to the main()
method. Since there is no exception handling for this foobar() method, the
program will terminate displaying the error message and stack trace.
If we are using custom functional interfaces, then we can throw checked as well
as unchecked exceptions. Custom functional interfaces can be defined by using
the @FunctionalInterface keyword.
The following are some of the rules that have to be followed while overriding method
throwing Exception:
Rule 1: If the parent class method is not throwing any exceptions, then the
overridden child class method should not throw checked exceptions. But it can throw
an unchecked exception. Consider an example that demonstrates this- We have 2
classes - ParentDemo and ChildDemo where the latter is the subclass of the
ParentDemo class. We have the doThis() the method that is overridden in the
ChildDemo class. The overridden method may only throw an unchecked exception.
The below example is valid since IllegalArgumentException is an unchecked
exception.
class ParentDemo {
void doThis() {
// ...
}
}
Rule 2: If the parent class method is throwing one or more checked exceptions, then
the overridden method in the child class can throw any unchecked exceptions or any
exceptions that are the same as checked exceptions of the parent method or the
subclasses of those checked exceptions. Consider the below example code:
class ParentDemo {
void doThis() throws IOException, ParseException {
// ...
}
In this example, the doThis() method throws few exceptions than the parent
method and the doThat() method throws a greater number of exceptions,
however, the scope of the exceptions is not greater than the parent exceptions. If we
try to throw a checked exception that was not declared in the parent method or we
throw an exception that has a broader scope, then it results in a compilation error.
For example, the below code is not valid as the parent method throws a
FileNotFoundException exception and the child method throws IOException which
is broader in scope as it is the parent class of FileNotFoundException :
class ParentDemo {
void doThis() throws FileNotFoundException {
// ...
}
}
Rule 3: If the parent class method has a throws clause having unchecked exceptions,
then the overriding child method can throw any number of unchecked exceptions
even if they are not related to each other. Consider the below example. While the
parent class doThis() method threw only 1 unchecked exception which is
IllegalArgumentException , the child class could throw multiple unchecked
exceptions as shown below:
class ParentDemo {
void doThis() throws IllegalArgumentException {
// ...
}
}
Use Specific Exception as much as possible for the sake of better messages and
easier debugging.
Throw Exceptions early in the program. This follows the Fail-Fast approach to
development.
Catch Exceptions late in the program, i.e, the caller has to handle the
exceptions.
If you are using Java 7 and above versions, make use of the feature of the try-
with-resources block to close the resources properly. In this way, we do not have
to remember to ensure that all resources have been closed in the finally block.
Always log the exception messages with meaningful messages. This helps in
easier debugging.
Use multiple catches that follow the rule of most specific exceptions at the top
and the most generic exceptions at the bottom.
If the exception types provided by Java do not match your use case, make sure
to use custom exceptions with meaningful error messages.
While creating custom messages, the naming convention of ending the
exception name with Exception has to be followed.
Whenever your method throws any exception, document this using the Javadoc
and describe that briefly using the @throws parameter.
Since exceptions are costly, be responsible while throwing them. Only throw
them if it makes sense.
Conclusion
Useful Resources
https://www.interviewbit.com/problems/exception-handling/
https://www.interviewbit.com/problems/try-catch-block/
https://www.scaler.com/topics/java/error-vs-exception-in-java/
https://www.interviewbit.com/technical-interview-questions/
Css Interview Questions Laravel Interview Questions Asp Net Interview Questions