Ans: Exception handling is the process of responding to the occurrence, during computation, of exceptions – anomalous or exceptional conditions requiring special processing – often changing the normal flow of program execution.
An exception is an abnormal event that occurs during the execution of a program and disrupts flow of the program’s instructions.
Ans: Traditional error detection and handling techniques often lead to spaghetti code hard to maintain and difficult to read. However, exceptions enable us to separate the core logic of our application from the details of what to do when something unexpected happens.
Also, since the JVM searches backward through the call stack to find any methods interested in handling a particular exception; we gain the ability to propagate an error up in the call stack without writing additional code.
Also, because all exceptions thrown in a program are objects, they can be grouped or categorized based on its class hierarchy. This allows us to catch a group exceptions in a single exception handler by specifying the exception’s superclass in the catch block.
Ans: There are four keywords used in java exception handling.
throws
keyword. We can provide multiple exceptions in the throws clause and it can be used with main() method also.Ans: A checked exception must be handled within a try-catch block or declared in a throws clause; whereas an unchecked exception is not required to be handled nor declared.
Checked and unchecked exceptions are also known as compile-time and runtime exceptions respectively.
All exceptions are checked exceptions, except those indicated by Error, RuntimeException, and their subclasses.
Ans: The throws keyword is used to specify that a method may raise an exception during its execution. It enforces explicit exception handling when calling a method:
public
void
simpleMethod()
throws
Exception {
// ...
}
The throw keyword allows us to throw an exception object to interrupt the normal flow of the program. This is most commonly used when a program fails to satisfy a given condition:if
(task.isTooComplicated()) {
throw
new
TooComplicatedException(
"The task is too complicated"
);
}
Ans: 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:
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.
Ans: Exception and all of it’s subclasses doesn’t provide any specific methods and all of the methods are defined in the base class Throwable:
getMessage()
method to return the exception message.Ans: Occurs when an exception is thrown in response to another exception. This allows us to discover the complete history of our raised problem:
try
{
task.readConfigFile();
}
catch
(FileNotFoundException ex) {
throw
new
TaskException(
"Could not perform task"
, ex);
}
Ans: By using a try-catch-finally statement:
try:
{
// ...
}
catch
(ExceptionType1 ex) {
// ...
}
catch
(ExceptionType2 ex) {
// ...
}
finally
{
// ...
}
The block of code in which an exception may occur is enclosed in a try block. This block is also called “protected” or “guarded” code.
If an exception occurs, the catch block that matches the exception being thrown is executed, if not, all catch blocks are ignored.
The finally block is always executed after the try block exits, whether an exception was thrown or not inside it.
Ans: A stack trace provides the names of the classes and methods that were called, from the start of the application to the point an exception occurred.
It’s a very useful debugging tool since it enables us to determine exactly where the exception was thrown in the application and the original causes that led to it.
Ans: Final and finally are keywords in java whereas finalize is a method.
Final keyword can be used with class variables so that they can’t be reassigned, with class to avoid extending by classes and with methods to avoid overriding by subclasses, finally keyword is used with try-catch block to provide statements that will always gets executed even if some exception arises, usually finally is used to close resources. finalize() method is executed by Garbage Collector before the object is destroyed, it’s great way to make sure all the global resources are closed.
Ans: When exception is thrown by main() method, Java Runtime terminates the program and print the exception message and stack trace in system console.
Ans: We can have an empty catch block but it’s the example of worst programming. We should never have empty catch block because if the exception is caught by that block, we will have no information about the exception and it wil be a nightmare to debug it. There should be at least a logging statement to log the exception details in console or log files.
Ans: OutOfMemoryError in Java is a subclass of java.lang.VirtualMachineError and it’s thrown by JVM when it ran out of heap memory. We can fix this error by providing more memory to run the java application through java options.
Ans: If you are catching a lot of exceptions in a single try block, you will notice that catch block code looks very ugly and mostly consists of redundant code to log the error, keeping this in mind Java 7 one of the feature was multi-catch block where we can catch multiple exceptions in a single catch block. The catch block with this feature looks like below:
catch(IOException | SQLException | Exception ex){
logger.error(ex);
throw new MyException(ex.getMessage());
}
Most of the time, we use finally block just to close the resources and sometimes we forget to close them and get runtime exceptions when the resources are exhausted. These exceptions are hard to debug and we might need to look into each place where we are using that type of resource to make sure we are closing it. So java 7 one of the improvement was try-with-resources where we can create a resource in the try statement itself and use it inside the try-catch block. When the execution comes out of try-catch block, runtime environment automatically close these resources. Sample of try-catch block with this improvement is:
try (MyResource mr = new MyResource()) {
System.out.println("MyResource created in try-with-resources");
} catch (Exception e) {
e.printStackTrace();
}
Ans: Some of the common main thread exception scenarios are:
Ans: Integer[][] ints = { {
1
,
2
,
3
}, {
null
}, {
7
,
8
,
9
} };
System.out.println(
"value = "
+ ints[
1
][
1
].intValue());
It throws an ArrayIndexOutOfBoundsException since we’re trying to access a position greater than the length of the array.
Ans: void
doSomething() {
// ...
throw
new
RuntimeException(
new
Exception(
"Chained Exception"
));
}
Yes. When chaining exceptions, the compiler only cares about the first one in the chain and, because it detects an unchecked exception, we don’t need to add a throws clause.
Ans: Yes. We can take advantage of the type erasure performed by the compiler and make it think we are throwing an unchecked exception, when, in fact; we’re throwing a checked exception:
public
<T
extends
Throwable> T sneakyThrow(Throwable ex)
throws
T {
throw
(T) ex;
}
public
void
methodWithoutThrows() {
this
.<RuntimeException>sneakyThrow(
new
Exception(
"Checked Exception"
));
}
Ans: Some of the best practices related to Java Exception Handling are: