Journaldev core java interview questions – Exception Handling Interview Questions in Java

Journaldev core java interview questions: List of topic-wise frequently asked java interview questions with the best possible answers for job interviews.

Exception Handling Interview Questions in Java

Question 1.
What is an Exception in Java?
Answer:
An exception is an error event that can happen during the execution of a program and disrupts its normal flow. An exception can arise from different kinds of situations such as wrong data entered by the user, hardware failure, network connection failure, etc.

Whenever any error occurs while executing a java statement, an exception object is created, and then JREtries to find an exception handler to handle the exception. If a suitable exception handler is found then the exception object is passed to the handler code to process the exception, known as catching the exception. If no handler is found then the application throws the exception to the runtime environment and JRE terminates the program.

Java Exception handling framework is used to handle runtime errors only, compile-time errors are not handled by exception handling framework.

Question 2.
What are the different kinds of exceptions? How do you catch a Runtime exception?
Answer:
There are 2 types of exceptions.

  1. Checked exception
  2. Unchecked exception.

The checked exception is cached at the compile-time while the unchecked exception is checked at run time.
1. Checked Exceptions: Environmental error that cannot necessarily be detected by testing; e.g. disk full, broken socket, database unavailable, etc.
2. Unchecked exception. Errors: Virtual machine error: class not found, out of memory, no such method, illegal access to a private field, etc.
Runtime Exceptions: Programming errors that should be detected in testing: index out of bounds, null pointer, illegal argument, etc. Checked exceptions must be handled at compile time. Runtime exceptions do not need to be. Errors often cannot be.

Question 3.
What is the Exception Handling Keywords in Java?
Answer:
There are four keywords used in java exception handling.

• throw: Sometimes we explicitly want to create an exception object and then throw it to halt the normal processing of the program, throw keyword is used to throw exceptions to the runtime to handle it.

• throws: When we are throwing any checked exception in a method and not handling it, then we need to use the throws keyword in the method signature to let the caller program know the exceptions that might be thrown by the method. The caller method might handle these exceptions or propagate them to its caller method using the throws keyword. We can provide multiple exceptions in the throws clause and it can be used with the main( ) method also.

• try-catch: We use try-catch block for exception handling in our code, try is the start of the block and catch is at the end of the try block to handle the exceptions. We can have multiple catch blocks with a try and try-catch block can be nested also, the catch block requires a parameter that should be of type Exception.

• finally: finally block is optional and can be used only with a try-catch block. Since exception halts the process of execution, we might have some resources open that will not get closed, so we can use finally block, finally block gets executed always, whether an exception occurs or not.

Question 4.
Explain Java Exception Hierarchy?
Answer:
Java Exceptions are hierarchical and inheritance is used to categorize different types of exceptions. Throwable is the parent class of Java Exceptions Hierarchy and it has two child objects – Error and Exception. Exceptions are further divided into checked exceptions and runtime exceptions.

Errors are exceptional scenarios that are out of the scope of application and it’s not possible to anticipate and recover from them, for example, hardware failure, JVM crash, or out of memory error.

Checked Exceptions are exceptional scenarios that we can anticipate in a program and try to recover from it, for example, FileNotFoundException. We should catch this exception and provide a useful message to the user and log it properly for debugging purposes. The exception is the parent class of all Checked Exceptions.

Runtime Exceptions are caused by bad programming, for example, trying to retrieve an element from the Array. We should check the length of the array first before trying to retrieve the element otherwise it might throw ArraylndexOutOfBoundException at runtime. RuntimeException is the parent class of all runtime exceptions.

Question 5.
What are the important methods of the Java Exception Class?
Answer:
Exception and all of its subclasses don’t provide any specific methods and all of the methods are defined in the base class Throwable.
• String get messages( ) – This method returns the message String of Throwable and the message can be provided while creating the exception through its constructor.

• String getLocalizedMessage( ) – This method is provided so that subclasses can override it to provide a locale-specific message to the calling program. Throwable class implementation of this method simply uses the get messages( ) method to return the exception message.

• synchronized Throwable getCause( ) — This method returns the cause of the exception or null if the cause is unknown.

• String to string( ) – This method returns the information about Throwable in String format, the returned String contains the name of Throwable class and localized message.

• void printStackTrace( ) – This method prints the stack trace information to the standard error stream, this method is overloaded and we can pass PrintStream or PrintWriter as arguments to write the stack trace information to the file or stream.

Question 6.
What is the difference between exception and error?
Answer:
The exception class defines mild error conditions that your program encounters.
Ex: ArithmeticException, FileNotFound exception
Exceptions can occur when trying to open the file, which does not exist

  • the network connection is disrupted
  • operands being manipulated are out of prescribed ranges
  • the class file you are interested in loading is missing

The error class defines serious error conditions that you should not attempt to recover from. In most cases, it is advisable to let the program terminate when such an error is encountered.
Ex: Running out of memory error, Stack overflow error.

Question 7.
Explain Java 7 ARM Feature and multi-catch block?
Answer:
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 features was the 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 improvements 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 the try-catch block, the runtime environment automatically closes these resources. Sample of the 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( );
}

Question 8.
What is the difference between Checked and Unchecked Exception in Java?
Answer:
• Checked Exceptions should be handled in the code using try-catch block or else the main( ) method should use throws keyword to let JRE know about this exception that might be thrown from the program. Unchecked Exceptions are not required to be handled in the program or to mention them in a throws clause.

• Exception is the superclass of all checked exceptions whereas RuntimeException is the superclass of all unchecked exceptions.

• Checked exceptions are error scenarios that are not caused by the program, for example, FileNotFoundException in reading a file that is not present, whereas Unchecked exceptions are mostly caused by poor programming, for example, NullPointerException when invoking a method on an object reference without making sure that it’s not null.

Question 9.
What is the difference between the throw and throws keyword in Java?
Answer:
throws keyword is used with method signature to declare the exceptions that the method might throw whereas throw keyword is used to disrupt the flow of the program and handing over the exception object to runtime to handle it.

Question 10.
How to write custom exceptions in Java?
Answer:
We can extend the Exception class or any of its subclasses to create our custom exception class. The custom exception class can have its own variables and methods that we can use to pass error codes or other exception-related information to the exception handler.
A simple example of custom exception is shown below.

MyException.java

package com.journaldev.exceptions;
import java.io.IOException;
public class MyException extends IoException {
private static final long serialversionUID = 4664456874499611218L;
private String errorcode=”unknown_Exception”;
public MyException(String message, String errorCode){
super(message);
this.errorCode=errorCode;
}
public string getErrorcode( ){
return this.errorCode;
}
}

Question 11.
What is OutOfMemoryError in Java?
Answer:
OutOfMemoryError in Java is a subclass of java. lang.VirtualMachineError and its thrown by JVM when it ran out of heap memory, and no more memory could be made available by the garbage collector. We can fix this error by providing more memory to run the java application through java options.

$>java MyProgram -xmsl024m -Xmxl024m -xx:Permsize=64M 
-xx:Max Pe rmSize=2 56m
Question 12.
What are different scenarios causing “Exception in thread main”?
Answer:
Some of the common main thread exception scenarios are:
• Exception in thread main java. lang.UnsupportedClassVersionError: This exception comes when your java class is compiled from another JDK version and you are trying to run it from another java version.
• Exception in thread main java. lang.NoClassDefFoundError: There are two variants of this exception. The first one is where you provide the class full name with the .class extension. The second scenario is when a Class is not found.
• Exception in thread main java. lang.NoSuchMethodError: main: This exception comes when you are trying to run a class that doesn’t have a main method.
• Exception in thread “main” java. lang.ArithmeticException: Whenever an exception is thrown from the main method, it prints the exception in the console. The first part explains that exception is thrown from the main method, the second part prints the exception class name and then after a colon, it prints the exception message.
Question 13.
What happens when an exception is thrown by the main method?
Answer:
When an exception is thrown by the main( ) method, Java Runtime terminates the program and prints the exception message and stack trace in the system console.
Question 14.
Can an exception be rethrown?
Answer:
Yes, an exception can be rethrown.
Question 15.
When is the final clause of a try-catch-finally statement executed?
Answer:
The final clause of the try-catch-finally statement is always executed unless the thread of execution terminates or an exception occurs within the execution of the final clause.
Question 16.
What class of exceptions are generated by the Java run-time system?
Answer:
The Java runtime system generates RuntimeException and Error exceptions.
Question 17.
What is the relationship between a method’s throws clause and the exceptions that can be thrown during the method’s execution?
Answer:
A method’s throws clause must declare any checked exceptions that are not caught within the body of the method.
Question 18.
What classes of exceptions may be thrown by a throw statement?
Answer:
A throw statement may throw any expression that may be assigned to the Throwable type.
Question 19.
What happens if an exception is not caught?
Answer:
An uncaught exception results in the uncaught exception( ) method of the thread’s ThreadGroup being invoked, which eventually results in the termination of the program in which it is thrown.
Question 20.
What happens if a try-catch-finally statement does not have a catch clause to handle an exception that is thrown within the body of the try statement?
Answer:
The exception propagates up to the next higher level try-catch statement (if any) or results in the program’s termination.
Question 21.
Can try statements be nested?
Answer:
Try statements may be tested.
Question 22.
How does a try statement determine which catch clause should be used to handle an exception?
Answer:
When an exception is thrown within the body of a try statement, the catch clauses of the try statement are examined in the order in which they appear. The first catch clause that is capable of handling the exception is executed. The remaining catch clauses are ignored.
Question 23.
What is the purpose of the final clause of a try-catch-finally statement?
Answer:
The final clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught.
Question 24.
Is it necessary that each try block must be followed by a catch block?
Answer:
It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block OR a final block. And whatever exceptions are likely to be thrown should be declared in the throws clause of the method
Question 25.
What classes of exceptions may be caught by a catch clause?
Answer:
A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types. Errors are generally irrecoverable conditions.
Question 26.
Can we have an empty catch block?
Answer:
We can have an empty catch block but it’s an example of worst programming. We should never have an empty catch block because if the exception is caught by that block, we will have no information about the exception and it will be a nightmare to debug it. There should be at least a logging statement to log the exception details in the console or log files.
Provide some Java Exception Handling Best Practices?
Some of the best practices related to Java Exception Handling are:
  • Use Specific Exceptions for ease of debugging.
  • Throw Exceptions Early (Fail-Fast) in the program.
  • Catch Exceptions late in the program, let the caller handle the exception.
  • Use Java 7 ARM feature to make sure resources are closed or use a final block to close them properly.
  • Always log exception messages for debugging purposes.
  • Use a multi-catch block for cleaner close.
  • Use custom exceptions to throw a single type of exception from your application API.
  • Follow naming convention, always end with Exception.
  • Document the Exceptions Thrown by a method using @throws in java does.
  • Exceptions are costly, so throw it only when it makes sense. Else you can catch them and provide a null or empty response.
Question 27.
What is the use of the final block?
Answer:
Finally is the block of code that is always executed even when an exception has occurred.
Question 28.
Does the code in the final block get executed if there is an exception and a return statement in a catch block?
Answer:
If an exception occurs and there is a return statement in the catch block, the final block is still executed. The final block will not be executed when the System. exit(l) statement is executed earlier or the system shut down earlier or the memory is used up earlier before the thread goes to finally block.
Question 29.
Does the code in the final block get executed if there is an exception and a return statement in a catch block?
Or
What is the purpose of the final clause of a try-catch-finally statement?
Answer:
 The final clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught. If an exception occurs and there is a return statement in the catch block, the final block is still executed. The final block will not be executed when the System. exit(O) statement is executed earlier or on the system shut down earlier or the memory is used up earlier before the thread goes to finally block.
try{
//some statements
}
catch{
//statements when exception is caught } 
finally{
//statements executed whether exception occurs or not
}

Question 30.
Does the order of placing catch statements matter in the catch block?
Answer:
Yes, it does. The FileNoFoundException is inherited from the IOException. So FileNoFoundException is caught before IOException. Exception’s subclasses have to be caught first before the General Exception

Question 31.
Explain the user-defined Exceptions?
Answer:
User-defined Exceptions are custom Exception classes defined by the user for a specific purpose. A user-defined exception can be created by simply sub-classing an Exception class or a subclass of an Exception class. This allows custom exceptions to be generated (using throw clause) and caught in the same way as normal exceptions.
Example:
class CustomException extends Exception {
}
Question 32.
When is finally block NOT called?
Answer:
  • Finally block is NOT called in the following cases: If the JVM exits while the try or catch code is being executed. This may happen due to System. exit( ) call.
  • If the thread executing the try or catch code gets interrupted or killed. In this case, the final block may not execute although the application keeps working.
  • If an exception is thrown in finally block is not handled. In this case, the remaining code in the final block may not execute.
Question 33.
What is the difference between final, finally, and finalize( )?
Answer:
final:
  • It is a modifier that can be applied to a class, method, or variable.
  • It is not possible to inherit the final class, override the final method and change the final variable.
finally:
  • It is an exception handling code section.
  • It gets executed whether an exception is raised or not by the try block code segment.
finalize( )
  • It is a method of Object class.
  • It is executed by the JVM just before garbage collecting object to give a final chance for resource releasing activity.
Out of the three, only finally is related to java exception handling.
Question 34.
What is the difference between throws and throws?
Answer:
Throw keyword Throws keywords
1. throw is used to explicitly throw an exception. Throws is used to declare an exception.
2. checked exceptions cannot be propagated with throw only. Checked exception can be propagated with throws.
3. throw is followed by an instance. Throws is followed by class.
4. throw is used within the method. Throws Is used with the method signature.
5. you cannot throw multiple exceptions You can declare multiple exception e.g. public void method( ) throws IOException , SQL Exception

Question 35.
What things should be kept in mind while creating your own exceptions in Java?
Answer:
While creating your own exception:

  • All exceptions must be a child of Throwable.
  • If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class.
  • You want to write a runtime exception, you need to extend the RuntimeException class.

Question 36.
What is NullPointerException?
Answer:
A NullPointerException is thrown when calling the instance method of a null object, accessing or modifying the field of a null object, etc.

Question 37.
Does it matter in what order catch statements for FileNotFoundException and IoException are written?
Answer:
Yes, it does. The FileNoFoundException is inherited from the IoException. Exception’s subclasses have to be caught first.

Question 38.
When is the ArrayStpreException thrown?
Answer:
When copying elements between different arrays, if the source or destination arguments are not arrays or their types are not compatible, an ArrayStoreException will be thrown.

Question 39.
When ArithmeticException is thrown?
Answer:
The ArithmeticException is thrown when an integer is divided by zero or taking the remainder of a number by zero. It is never thrown in floating-point operations.

Question 40.
What will happen if the static modifier is removed from the signature of the main method?
Answer:
The program throws a “NoSuchMethodError” error at runtime.

Question 41.
If System. exit (0); is written at the end of the try block, will the finally block still execute?
Answer:
No in this case the final block will not execute because when you say System. exit (0); the control immediately goes out of the program, and thus finally never executes.

Question 42.
When is the ArrayStoreException thrown?
Answer:
When copying elements between different arrays, if the source or destination arguments are not arrays or their types are not compatible, an ArrayStoreException will be thrown.

Question 43.
What is the problem with following code?
if (x == null && x.getMethodO == true)
Answer:
It will throw NPE in case x is null.

Question 44.
What is an Assertion and why using assertion in your program is a good idea?
Answer:
In a Java program, several times, one would like to make certain assumptions for executing a program. For example, while taking a square root of a numeric value it has to be assumed that this value should not be negative. An assertion is a statement in the Java programming language that enables to test assumptions about one’s program. Assertions are supported from J2SE1.4 and later. A simple example of assertion can be checking off an employee object from being null: Employee employee = null;

Question 45.
Explain Assertions with a code example.
Answer:
The main reason for introducing assertions in Java from R1.4 onwards is to reduce the chances of bugs that otherwise would have gone unnoticed, in one’s code. In fact, finding and removing bugs is one tedious and not-so-exciting task. Assertions should be used for scenarios that ideally should never happen in the lifecycle of a program, check assumptions about data structures (such as ensuring that an array is. of the correct length), or enforcing constraints on arguments of private methods. Assertions help in a way to block these bugs at the beginning of writing actual logic inside your code that saves a lot of effort, time, and most significantly, costs. A simple assertion facility provides a limited form of design-by-contract programming.

In design-by-contract programming identification of preconditions and postconditions to a program are a must before even starting the coding itself. Here is simple Java code which uses assertions; here the task is to determine the gender of a person. We have used a switch-case statement to define the overall flow of the logic.

Question 46.
How many forms of assertions do we have?
Answer:
There are two forms of assertions:
The first, simpler form is:
assert Expression 1;
where Expression 1 is a boolean expression.
When the system runs the assertion, it evaluates Expression 1 and if it is false throws an AssertionError with no detailed message.
While the second form of the assertion statement is:
assert Expression1: Expression2;
where: Expression1 is a boolean expression.
Expression2 is an expression that has a value. (It cannot be an invocation of a method that is declared void.)
This form is used when the assert statement has to provide a detailed message for the AssertionError. The system passes the value of Expression2 to the appropriate AssertionError constructor, and this constructor uses the string representation of the value as the error’s detail message. This detailed message helps in analyzing and diagnosing the assertion failure which ultimately helps in resolving the error.

Question 47.
When assertions should be avoided?
Answer:
In the following situations the assertions should be avoided:

  • When assertion becomes a performance issue. It means an assertion should not include too complex logic equaling the implementation of a method.
  • Do not use assertions in argument checking of public methods. As argument checking is part of a method implementation and if these arguments are erroneous then it will throw runtime exception and. assertion failure will not result in any error.

Question 48.
What situations are best suitable for implementing assertions?
Answer:
Assertions can best be implemented:

  • As Internal Invariants
  • As Control flow Invariants
  • As Preconditions and Postconditions
  • As Class Invariants.

Question 49.
If my class already extends from some other class what should I do if I want an instance of my class to be thrown as an exception object?
Answer:
One cannot do anything in this scenario. Because Java does not allow multiple inheritances and does not provide any exception interface as well.

Question 50.
How does an exception permeate through the code?
Answer:
An unhandled exception moves up the method stack in search of a matching When an exception is thrown from a code that is wrapped in a try block followed by one or more catch blocks, a search is made for a matching catch block. If a matching type is found then that block will be invoked. If a matching type is not found then the exception moves up the method stack and reaches the caller method. The same procedure is repeated if the caller method is included in a try catch block. This process continues until a catch block handling the appropriate type of exception is found. If it does not find such a block then finally the program terminates.

Question 51.
What are the different ways to handle exceptions?
Answer:
There are two ways to handle exceptions,

  1. By wrapping the desired code in a try block followed by a catch block to catch the exceptions. And
  2. List the desired exceptions in the throws clause of the method and let the caller of the method handle those exceptions.

Question 52.
What is the basic difference between the 2 approaches to exception handling?

  1. try catch block and
  2. Specifying the candidate exceptions in the throws clause?

When should you use which approach?
Answer: In the first approach as a programmer of the method, you urself are dealing with the exception. This is fine if you are in the best position to decide what should be done in case of an exception. Whereas if it is not the responsibility of the method to deal with its own exceptions, then do not use this approach. In this case, use the second approach. In the second approach, we are forcing the caller of the method to catch the exceptions that the method is likely to throw. This is often the approach library creators use. They list the exception in the throws clause and we must catch them. You will find the same approach throughout the java libraries we use.

Question 53.
Is it necessary that each try block must be followed by a catch block?
Answer:
It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block OR a final block. And whatever exceptions are likely to be thrown should be declared in the throws clause of the method.

Question 54.
If I write return at the end of the try block, will the finally block still execute?
Answer:
Yes even if you write return as the last statement in the try block and no exception occurs, the final block will execute. The final block will execute and then the control return.