Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Exception Handling Interview Questions and Answers

by Mohammed, on Mar 24, 2018 11:42:31 AM

Exception Handling Interview Questions and Answers

Q1. What is an exception Handling?

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.

Q2. What are some advantages of exceptions?

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.

Q3. What are the Exception Handling Keywords in Java?

Ans: There are four keywords used in java exception handling.

  1. throw: Sometimes we explicitly want to create exception object and then throw it to halt the normal processing of the program. throw keyword is used to throw exception to the runtime to handle it.
  2. throws: When we are throwing any checked exception in a method and not handling it, then we need to use throws keyword in method signature to let caller program know the exceptions that might be thrown by the method. The caller method might handle these exceptions or propagate it to it’s caller method using throws keyword. We can provide multiple exceptions in the throws clause and it can be used with main() method also.
  3. 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 try block to handle the exceptions. We can have multiple catch blocks with a try and try-catch block can be nested also. catch block requires a parameter that should be of type Exception.
  4. finally: finally block is optional and can be used only with 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 exception occurrs or not.

Q4. What is the difference between a checked and an unchecked exception?

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.

Q5. What is the purpose of the throw and throwskeywords?

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" );
}

Q6. What is the difference between an exception and error?

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:

  • OutOfMemoryError: Thrown when the JVM cannot allocate more objects because it is out memory, and the garbage collector was unable to make more available.
  • StackOverflowError: Occurs when the stack space for a thread has run out, typically because an application recurses too deeply.
  • ExceptionInInitializerError: signals that an unexpected exception occurred during the evaluation of a static initializer.
  • NoClassDefFoundError: is thrown when the classloader tries to load the definition of a class and couldn’t find it, usually because the required classfiles were not found in the classpath.
  • UnsupportedClassVersionError: occurs when the JVM attempts to read a class file and determines that the version in the file is not supported, normally because the file was generated with a newer version of Java.

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.

 

Q7. What are important methods of Java Exception Class?

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:

  • String getMessage(): This method returns the message String of Throwable and the message can be provided while creating the exception through it’s constructor.
  • String getLocalizedMessage(): This method is provided so that subclasses can override it to provide locale specific message to the calling program. Throwable class implementation of this method simply use getMessage() method to return the exception message.
  • Synchronized Throwable getCause(): This method returns the cause of the exception or null id the cause is unknown.
  • String toString(): 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 argument to write the stack trace information to the file or stream.

Q8. What is exception chaining?

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);
}

 

Q9. How can you handle an exception?

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.

Q10. What is a stacktrace and how does it relate to an exception?

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.

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

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.

Q12. What happens when exception is thrown by main method?

Ans: When exception is thrown by main() method, Java Runtime terminates the program and print the exception message and stack trace in system console.

Q13. Can we have an empty catch block?

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.

Q14. What is OutOfMemoryError in Java?

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.

Q15. Explain Java 7 ARM Feature and multi-catch block?

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

}

Q16. What are different scenarios causing “Exception in thread main”?

Ans: 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 .class extension. The second scenario is when 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 main method.
  • Exception in thread “main” java.lang.ArithmeticException: Whenever any exception is thrown from main method, it prints the exception is console. The first part explains that exception is thrown from main method, second part prints the exception class name and then after a colon, it prints the exception message.

Q17. What exception will be thrown executing the following code block?

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.

Q18. Will the following code compile?

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.

Q19.  Is there any way of throwing a checked exception from a method that does not have 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" ));
}
 

Q20. Provide some Java Exception Handling Best Practices?

Ans: 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 finally block to close them properly.
  • Always log exception messages for debugging purposes.
  • Use multi-catch block for cleaner close.
  • Use custom exceptions to throw 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 javadoc.
  • Exceptions are costly, so throw it only when it makes sense. Else you can catch them and provide null or empty response.
Topics:Exception Handling Interview Questions and AnswersInformation Technologies (IT)

Comments

Subscribe

Top Courses in Python

Top Courses in Python

We help you to choose the right Python career Path at myTectra. Here are the top courses in Python one can select. Learn More →

aathirai cut mango pickle

More...