Java – Interview question and answers on Exception Handling

In this article, we will cover some of the interview questions with their justification on Java Exception handling

These are most frequently asked interview question from Java Exception handling

Read Exception handling concepts in detail

1. Exception & Error:

Q) What is an Exception in Java ?

  • Exception: An event which disrupts normal execution of a program is known as exception

Q) What is an Exception handling in Java ?

  • When such event occurs during execution of the program, in Java terms it is called as exception thrown or exception raised at runtime
  • Which results in abrupt or abnormal termination of the program and rest of the program (code i.e.; after the line where exception is raised) won’t be executed
  • To avoid abnormal termination of the program, all possible exceptions that could be thrown/raised needs to be handled
  • This is known as exception handling in Java
  • This helps to maintain graceful termination of the program
  • Read Exception handling in Java for more detail

Q) Explain exception hierarchy in Java ?

  • Throwable class is the root class for every exception and it branches out to 2 main categories i.e.; Exception & Error
  • Read Exception hierarchy in Java in detail
  • Refer below figure for Exception hierarchy

Q) What is the difference between Exception v/s Error in Java ?

  • Both are sub-class of Throwable class
  • Error is due to lack of system resources and it is non-recoverable. Therefore it isn’t feasible to handled by programmer
  • Exception is due to programmatic logic and it is recoverable. Therefore it must be handled using either try-catch block or throws clause
  • Read Error v/s Exception in Java in detail

Q) What is the super class for Exception & Error in Java ?

  • java.lang.Throwable is the root class for all types of Error & Exception

Q) What is the difference between checked exception v/s unchecked exceptions in Java ?

Checked Exception

Unchecked Exception

Exception which are checked at compile-time during compilation is known as Checked ExceptionException which are NOT checked at compile-time is known as Unchecked Exception
Alternate definition: any line of code that could possibly throw exception, and if raised during compilation is said to be checked exceptionAlternate definition: any line of code that could possibly throw exception at runtime is said to be unchecked exception
Except Runtime exception & its child classes and error & its child classes, all other exception fall under the category of Checked ExceptionExample of unchecked-exception :

 

  • Runtime exception & its child classes
  • error & its child classes
Some of the checked exception

 

  • IOException
  • SQLException
  • InterruptedException
  • etc
Some of the unchecked exception

 

  • RuntimeException
  • NullPointerException
  • ArithmeticException
  • etc

Q) Explain important keywords in Java Exception handling ?

Read 5 important keywords in Java Exception handling in detail with examples

  1. try
  2. catch
  3. finally
  4. throw
  5. throws

2. try-catch-finally blocks combination:

Q) Is it valid to keep only try-block without catch-block or finally-block ?

  • No, keeping only try-block will raise compile-time error stating “Syntax error, insert “Finally” to complete BlockStatements
  • There are 3 possible combination for try block
  • 1st combination : try-block is followed by catch-block only
  • 2nd combination : try-block is followed by finally-block only
  • 3rd  combination : is sequence of try-catch-finally block
  • The only other possible combination is, try block followed by multiple catch blocks

Q) Whether multiple catch is possible for single try-block ?

  • Yes, it is very much possible to declare multiple catch block for single try-block
  • Example, as shown in the below screen-capture

 

Q) What are rules for declaring multiple catch-blocks ? 

  • For try with multiple catch block, order of exception declaration is very important
  • That’s, most specific exception must come up 1st in the order and followed by more general exception
  • In other words, if there exists parent-child relationship between 2 exception then child exception must come 1st up in the order and then followed by parent exception
  • Otherwise, compile-time error will be thrown stating “Exception <name-of-exception> has already been caught
  • Also, declaring multiple catch with same type of exception results in compile-time error stating “Unreachable catch block for <exception-type>. It is already handled by the catch block for <exception-type>
  • Read try with multiple catch block for details

Q) Whether it is very mandatory to include curly braces for try-catch-finally block, what happens if not included ?

  • Yes, it is must to include curly braces for try-block, catch-block and finally-block even if it contains just one line of code
  • Otherwise, compile-time error will be thrown as shown in the below screen-capture
  • Read try-catch block and finally block for details

Q) Whether nested try-catch block is possible inside outer try-catch block ?

  • Yes, nesting try-catch block inside another try-catch is possible & valid
  • It can be nested inside another try-block, catch-block or finally-block
  • Read nested try-catch block for details

 

Q) Can we write any Java statements in between try-block & catch-block ?

  • No, any statement in between try block & catch block results in compile-time error
  • Example, as shown in the below screen capture

Q) What is the main purpose of finally-block in Java ?

  • The main purpose of finally-block is to perform clean-up activities or code clean-up like closing database connection & closing streams or file resources, etc.
  • finally-block is always associated with try-catch block
  • Advantage: The beauty of finally-block is that, it is executed irrespective of whether exception is thrown or NOT and its handled or NOT
  • Read finally block in detail

 

Q) Can we have finally-block followed by try-block (without catch-block) ?

  • Yes, it is valid sequence to have try-block followed by finally-block (without catch-block or multiple block in between them)
  • Read finally block in detail to understand this sequence

 

Q) Whether it is possible to write any statements after finally-block ?

  • If there is no return statement for a method, then it is valid to write any valid statements after finally-block
  • But if there is a method that returns a value then writing any statement after finally-block results in compile-time error
  • If there is a return statement after finally-block, then it is valid
  • Read returning a value from method having try-catch-finally block for understanding all scenarios

Q) Whether finally-block always executed, irrespective of any exception ?

  • finally-block always executed irrespective of whether exception thrown or NOT and it is handled or NOT
  • But on one condition, finally-block wont executed when it encounters System.exit(0); method as it kills program execution further
  • Read return statement with finally block for understanding exit scenario

Q) Will finally-block always be executed, even if there is return statement inside both try-block or catch-block ? 

  • Yes, finally-block always executed even if there is a return statement inside try-catch block
  • Read return statement with finally block for understanding both valid & exception scenarios

Q) Explain various possible combinations to write return in a method enclosed with try-catch-finally block ?

Q) Whether exception raises from catch-block ?

  • It is very much possible that, code inside catch-block too raises exception and this need to be handled
  • Otherwise, program terminates abnormally

Q) Whether it is possible to declare catch-block with same exception-type twice, for example ArithmeticException ?

  • No, it isn’t possible to declare multiple catch with same exception-type
  • This leads to compile-time error stating “Unreachable catch block for ArithmeticException. It is already handled by the catch block for ArithmeticException
  • Example, as shown in the below screen-capture

3. Exception information:

Q) What are various methods available to print exception information in console ?

  • Whenever exception is raised. then respective method from where exception is raised is responsible for creating an exception object with following information like
    1. Name of the exception
    2. Description of the exception
    3. Location at which exception is raised i.e.; stack trace
  • Read Various methods to print exception information in Java for more detail
MethodDescriptionFormat
printStackTrace();Prints all details related to exception from exception object created by methodName-of-ex : Description-of-ex

 

At location (StackTrace)

toString();Returns name & description of the exception in String formatName-of-ex : Description-of-ex
getMessage();Returns detailed description of the exception thrownDescription-of-ex
getCause();Returns the cause of the exception;

 

Otherwise, returns null

Caused By: classname & stack trace

Q) Which method is used by default exception handler to print stack trace ?

  • printStackTrace(); method of Throwable class

4. throw & throws keywords and Custom Exception:

Q) Explain throw keyword with its rules ?

throw keyword:

  • User or programmer can also throw/raise exception explicitly at runtime on the basis of some business condition
  • To raise such exception explicitly during program execution, we need to use throw keyword
  • Syntax: throw instanceOfThrowableType;
  • The main purpose of throw keyword is used to throw user-defined exception or custom exception
  • Read throw keyword for more details

Rules:

  • Both checked & unchecked exception can be thrown using throw keyword
  • The caller-method has to handle exception, whenever target method declares exception using throw keyword
  • Any valid Java statement after throw keyword is not reachable and it raises compile-time error
  • Whenever thrown exception using throw keyword refers to null reference, then instead of throwing actual exception, NullPointerException will be thrown
  • Re-throwing: Caught exception in catch block can be re-thrown using throw keyword after some alteration

Q) Explain throws keyword with its rules ?

throws keyword:

  • throws keyword is used to declare exception that might raise during program execution
  • whenever exception might thrown from program, then programmer doesn’t necessarily need to handle that exception using try-catch block instead simply declare that exception using throws clause next to method signature
  • But this forces/tells caller-method to handle that exception; but again caller can handle that exception using try-catch block or re-declare those exception with throws clause
  • In other words it can also be stated that, it provides information to the caller method that possible exception might raise during program execution and it need to be handled
  • Read throws keyword for more detail

Rules:

  • Whenever exception is declared using throws clause by target method, then caller method must handle this exception-type
  • either using try-catch block or declaring throws clause mentioning exception-type
  • Any number of exceptions can be declared using throws clause, but they are all must be separated using commas (,)
  • Constructor can also declare exception using throws clause
  • User-defined exception or custom exception can also be declared using throws clause

Q) Can we declare unchecked exception using throws keyword in method signature ?

  • Yes, it is possible to declare unchecked exception using throws clause

Q) What happens, if there are some Java statements after explicit exception thrown using throw keyword ?

  • Compile-time error will be thrown stating “Unreachable code
  • Example, as shown in the below screen-capture

Q) Why only object of type Throwable (or its sub-type) is allowed to thrown ?

  • Using throw keyword, only exception can be thrown
  • Therefore, all exception thrown should fall in the exception hierarchy (extending any one of the types of Throwable class)
  • It can be checked or unchecked or user-define exception

Q) Whether it is valid to throw Java object, which isn’t extending any Exception/Error from exception hierarchy ?

  • As explained in the above question, only exception can be thrown which should extend any one of the types of Throwable class
  • Throwing normal Java object which isn’t extending any exception-type from exception hierarchy will results in compile-time error stating “incompatible types

Q) Whether it is a normal termination or abnormal termination, if we are using throws keyword ?

  • It’s a abnormal termination, irrespective of whether program raises any exceptions or NOT
  • When we are using throws keyword to handle any exception raised during program execution, then it is always considered as a abnormal termination

Q) Whether it is possible to create custom exception and can we throw this custom made exception ?

  • Yes, it is very much possible to create user-defined exception
  • Condition: while creating user-defined exception, it should extend any one of the types of Throwable class
  • Otherwise, while throwing user-defined exception a compile-time error will be thrown stating “incompatible types
  • Read User-defined exception or Custom exception for more details

Q) Whether it is possible to throw user-defined exception ?

  • Yes, it is possible to throw user-defined exception
  • The only condition is that it should extend any one of the types of Throwable class
  • Otherwise, while throwing user-defined exception a compile-time error will be thrown stating “incompatible types

Q) How to write custom exception, explain its steps ?

  • It is very simple
  • Write a Java class with any valid names adhering to Java syntax and extend any one of the types of Throwable class
  • Later, this exception can be used with throw, throws or catch keyword in exception handling

Q) Explain Exception propagation ?

Exception propagation:

  • Whenever exception is raised from method and if it isn’t handled in the same method, then it is propagated back to the caller method
  • This step is repeated until handler code is found in one of the caller method in the runtime stack or else it reaches the bottom of the runtime stack
  • This is known as Exception propagation
  • Read Exception propagation for more details

Rules for Exception propagation:

  • By default, unchecked exception is propagated back to the runtime stack one-by-one until it finds handler code or it reached the bottom of the stack
  • Checked exception isn’t propagated, rather compiler forces the programmer to handle checked exception in the same method by surrounding with try-catch block or declaring with throws keyword

Q) Explain re-throwing an exception ?

It is possible & valid to re-throw caught exception in the catch block. It is generally used in few cases,

  • When a method catches exception and doesn’t want to handle, instead it want to propagate exception to caller-method (basically delegating the responsibly to caller method)
  • Sometimes, method catches one exception-type and convert to another exception-type before throwing using throw clause
  • It is also used to add some user message to caught exception before re-throwing to caller-method
  • Note: in all cases, it the responsibility of the caller method to handle this exception whether by surrounding with try-catch or declare throws clause

5. Difference between:

Q) Difference between throw and throws keywords ?

throw clause/keywordthrows clause/keyword
throw keyword is used to throw exception explicitlythrows keyword is used to declare exception to delegate/indicate exception handling responsibility to caller method
throw keyword is always followed by instance of Throwable type or exception typethrows keyword is always followed by exception list (with comma separating them)
throw keyword is used within method i.e.; to throw exception from try-catch block enclosed within methodthrows keyword is used next to method signature
Syntax: throw instanceOfExceptionType;Syntax: access_modifier return_type method_name() throws exception_list;
Maximum of only one exception can be thrown using throw keyword

 

Thrown exception can be checked exception or unchecked exception or user-defined exception

Any number of exception can be thrown using throws keyword

 

But they are all separated by comma (,)

Q) Difference between try-catch block v/s throws keyword ?

try-catch blockthrows keyword
Using try-catch block, we can handle exception surrounding code that might raise an exceptionWhereas using throws keyword, we can simply declare exception that might raise from that method
Caught exception in the catch block can be re-thrown after some alterationThere is no such flexibility, as its directly throws exception
try-catch block ensures graceful termination for that particular method

 

Except one scenario when catch block throws exception

Doesn’t guarantee graceful termination

 

In most cases, throws declaration leads to abnormal termination

Q) Explain the different between final v/s finally v/s finalize() ?

  • final is a keyword used for restricting further alteration in inheritance
  • finally is associated with try-catch in exception handling for clean-up activity
  • finalize() is a method associated with garbage collector to de-allocate resource associated with Object
  • Read final v/s finally v/s finalize for more detail with examples

Q) Explain the difference between ClassNotFoundException v/s NoClassDefFoundError in detail ?

ClassNotFoundExceptionNoClassDefFoundError
This is generally occurs, when required .class is missing when program encounters class load statement such as,

 

  • Class.forName(“class.name”);
  • ClassLoader.loadClass(“class.name”);
  • ClassLoader.findSystemClass(“class.name”);

Reason: required file missing in the class-path during  execution of program without updating JAR file at runtime

This is very much similar but difference is required .class file is available during compile-time & missing at runtime

 

Possible Reason:

  • It is deleted after compilation or
  • there could be version mismatch
Fully qualified class name is java.lang.ClassNotFoundExceptionFully qualified class name is java.lang.NoClassDefFoundError
It falls under the category of Exception i.e.; direct sub-class of java.lang.ExceptionIt falls under the category of Error i.e.; sub-class of java.lang.Error through java.lang.LinkageError
It is a checked exception, therefore it needs to be handled, whenever class loading is encountered as stated in point no.1All errors come under unchecked exception category, therefore NoClassDefFoundError is also unchecked exception
As it is checked exception, programmer can provide handling code either using try-catch block or can declare throws clause

 

Therefore, it is recoverable

Errors are thrown by Java Runtime system during program execution

 

Therefore, it is non-recoverable

6. Java 1.7 version features:

Q) Explain, what are the new features introduced in Java 1.7 version ?

  • New featured introduced in Java 1.7 version are,
  • try-with-resources for automatic resource management
  • multi-catch block for grouping different exception-type for similar handler-code with pipe character separating them

Q) Explain Automatic Resource management feature in Java exception handling ?

try-with-resources statement:

  • Using try-with-resources statement, programmer doesn’t need to explicitly close opened resources
  • Rather it will be automatically closed once control reaches end of try-catch block
  • This new feature introduced in Java 1.7 version is alternatively referred as Automatic Resource Management i.e.; ARM
  • Read try-with-resources statement for more detail with example

Rules:

  • All resources declared as part of try-with-resources statement must be AutoCloseable (i.e.; all resources must implements java.lang.AutoCloseable interface)
  • Multiple resources can be declared inside try block argument; but they are all must be separated by semi-colon (;)
  • While using try-with-resources statement, try-block itself is enough. There is no compulsion to write/code either catch-block or finally-block followingtry block, whereas in prior versions try-block must be followed by either catch-block or finally-block
  • All resource reference variable declared inside try-block argument are implicitly final. Therefore, resource reference variable can’t changed or re-assigned within try-block

Q) Whether it is mandatory to follow catch-block or finally-block, after try-with-resources statement (try-block) ?

  • It isn’t mandatory to have either catch-block or finally-block following try-block
  • try-block alone can work without the need of catch-block or finally-block

Q) How is multi-catch block is useful over traditional multiple catch blocks ?

Multi-catch block:

  • In Java 1.6 or lesser version, whenever multiple exception is thrown, then programmer has to provide multiple catch block to catch different types of exception, although exception handling code is same
  • But in Java 1.7 version, we can write/code single catch block to handle multiple types of exceptions using multi-catch block
  • Multi-catch block helps to provide same handler-code by grouping different exception-types. And program/code becomes more readable with lesser lines of code
  • Read Multi catch block in Java 1.7 version for more detail with example

Rules:

  • There shouldn’t be any relationship between declared exception-type in multi-catch block.
  • Otherwise, compile-time error will be thrown stating “The exception <child-exception-type> is already caught by the alternative <parent-exception-type>
  • If a catch block handles more than one exception-type (i.e.; multi-catch block), then exception variable is implicitly final
  • Any changes or re-assignment to this implicit final variable within catch block results in compile-time error

7. Others:

Q) Explain rules for exception handling with respect to method overriding ?

Rule 1: If parent-class method doesn’t declare any exception,

  1. Then child-class overriding-method can declare any type of unchecked-exception (this is the only possibility)
  2. If child-class overriding-method declares checked-exception, then compiler throws compile-time error stating “Exception <exception-type> is not compatible with throws clause in ParentClass.testMethod()
  3. Then child-class overriding-method can declare no exception (this is very much same as that of overridden-method of parent-class –> exactly same method signature)

Rule 2: If parent-class method declares unchecked exception,

  1. Then child-class overriding-method can declare any type of unchecked-exception (not necessarily same exception as that of parent-class’ method)
  2. If child-class overriding-method declares any checked-exception, then compiler throws compile-time error stating “Exception <exception-type> is not compatible with throws clause in ParentClass.testMethod()
  3. Then child-class overriding-method can declare no exception

Rule 3: If parent-class method declares checked exception,

  1. Then child-class overriding-method can declare any type of unchecked-exception
  2. Then child-class overriding-method can declare same type of checked-exception or one of its sub-class or no exception
  3. Then child-class overriding-method can declare no exception

Rule 4: If parent-class method declares both checked & unchecked exceptions,

  1. Then child-class overriding method can declare any type of unchecked-exception
  2. Then child-class overriding-method can declare same type of checked-exception or one of its sub-class or no exception
  3. Then child-class overriding-method can declare no exception

Q) What are unreachable block in Java ?

There are various scenarios when this compile-time error is encountered

  • If there are any statement after throw clause
  • When declaring multiple catch blocks, parent-exception declared before than child-exception
  • Declaring catch-block for checked-exception, when actually try-block never going to throw that exception
  • Any valid Java statements after return statement
  • Any valid Java statement after finally-block, if finally-block is returning some value
  • Note: try examples on your own

Q) Does a method can return an exception ?

  • A method can only throw exception
  • Method can’t return exception
  • Note: until & unless method’s return-type itself is valid Exception or one of its sub-types

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java - Interview question and answer on super keyword
Java - Difference between ClassNotFoundException v/s NoClassDefFoundError ?