Java provides a robust and object-oriented approach to handle exception scenarios known as Java Exception Handling. Sometime back I wrote a long post on Exception Handling in Java and today I am listing some important Java Exceptions Questions with Answers to help you in interviews.
An exception is an error event that can happen during the execution of a program and disrupts its normal flow. The 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 JRE tries 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.
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 the main() method also.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. 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 ArrayIndexOutOfBoundException
at runtime. RuntimeException
is the parent class of all runtime exceptions.
Exception and all of its subclasses don’t provide any specific methods and all of the methods are defined in the base class Throwable.
getMessage()
method to return the exception message.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 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();
}
Read more about this at Java 7 ARM.
Exception
is the superclass of all checked exceptions whereas RuntimeException
is the superclass of all unchecked exceptions. Note that RuntimeException is the child class of Exception.FileNotFoundException
and we must catch it in the try-catch block or throw it again to the caller method. 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. For example, I can write a method to remove all the vowels from the string. It’s the caller’s responsibility to make sure not to pass a null string. I might change the method to handle these scenarios but ideally, the caller should take care of this.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.
We can extend 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 a custom exception is shown below.
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;
}
}
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. $>java MyProgram -Xms1024m -Xmx1024m -XX:PermSize=64M -XX:MaxPermSize=256m
Some of the common main thread exception scenarios are:
Read more about these at Java Exception in thread main.
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 the 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 get 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 a great way to make sure all the global resources are closed. Out of the three, only finally is related to java exception handling.
When an exception is thrown by a main() method, Java Runtime terminates the program and prints the exception message and stack trace in the system console.
We can have an empty catch block but it’s an example of bad 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 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.
Some of the best practices related to Java Exception Handling are:
Read more about them in detail at Java Exception Handling Best Practices.
In this section, we will look into some programming questions related to java exceptions.
What is the problem with the below program?
package com.journaldev.exceptions;
import java.io.FileNotFoundException;
import java.io.IOException;
public class TestException {
public static void main(String[] args) {
try {
testExceptions();
} catch (FileNotFoundException | IOException e) {
e.printStackTrace();
}
}
public static void testExceptions() throws IOException, FileNotFoundException{
}
}
The above program won’t compile and you will get an error message as “The exception FileNotFoundException is already caught by the alternative IOException”. This is because FileNotFoundException is a subclass of IOException, there are two ways to solve this problem. The first way is to use a single catch block for both the exceptions.
try {
testExceptions();
}catch(FileNotFoundException e){
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
Another way is to remove the FileNotFoundException from the multi-catch block.
try {
testExceptions();
}catch (IOException e) {
e.printStackTrace();
}
You can chose any of these approach based on your catch block code.
What is the problem with the below program?
package com.journaldev.exceptions;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.xml.bind.JAXBException;
public class TestException1 {
public static void main(String[] args) {
try {
go();
} catch (IOException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (JAXBException e) {
e.printStackTrace();
}
}
public static void go() throws IOException, JAXBException, FileNotFoundException{
}
}
The program won’t compile because FileNotFoundException is a subclass of IOException, so the catch block of FileNotFoundException is unreachable and you will get an error message as “Unreachable catch block for FileNotFoundException. It is already handled by the catch block for IOException”. You need to fix the catch block order to solve this issue.
try {
go();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JAXBException e) {
e.printStackTrace();
}
Notice that JAXBException is not related to IOException or FileNotFoundException and can be put anywhere in the above catch block hierarchy.
What is the problem with the below program?
package com.journaldev.exceptions;
import java.io.IOException;
import javax.xml.bind.JAXBException;
public class TestException2 {
public static void main(String[] args) {
try {
foo();
} catch (IOException e) {
e.printStackTrace();
}catch(JAXBException e){
e.printStackTrace();
}catch(NullPointerException e){
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
}
public static void foo() throws IOException{
}
}
The program won’t compile because JAXBException is a checked exception and foo() method should throw this exception to catch in the calling method. You will get an error message as “Unreachable catch block for JAXBException. This exception is never thrown from the try statement body”. To solve this issue, you will have to remove the catch block of JAXBException. Notice that catching NullPointerException is valid because it’s an unchecked exception.
What is the problem with the below program?
package com.journaldev.exceptions;
public class TestException3 {
public static void main(String[] args) {
try{
bar();
}catch(NullPointerException e){
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
foo();
}
public static void bar(){
}
public static void foo() throws NullPointerException{
}
}
This is a trick question, there is no problem with the code and it will compile successfully. We can always catch an Exception or any unchecked exception even if it’s not in the throws clause of the method. Similarly, if a method (foo) declares an unchecked exception in the throws clause, it is not mandatory to handle that in the program.
What is the problem with the below program?
package com.journaldev.exceptions;
import java.io.IOException;
public class TestException4 {
public void start() throws IOException{
}
public void foo() throws NullPointerException{
}
}
class TestException5 extends TestException4{
public void start() throws Exception{
}
public void foo() throws RuntimeException{
}
}
The above program won’t compile because the start() method signature is not the same in the subclass. To fix this issue, we can either change the method singnature in the subclass to be exactly the same as the superclass or we can remove the throws clause from the subclass method as shown below.
@Override
public void start(){
}
What is the problem with the below program?
package com.journaldev.exceptions;
import java.io.IOException;
import javax.xml.bind.JAXBException;
public class TestException6 {
public static void main(String[] args) {
try {
foo();
} catch (IOException | JAXBException e) {
e = new Exception("");
e.printStackTrace();
}catch(Exception e){
e = new Exception("");
e.printStackTrace();
}
}
public static void foo() throws IOException, JAXBException{
}
}
The above program won’t compile because the exception object in the multi-catch block is final and we can’t change its value. You will get compile time error as “The parameter e of a multi-catch block cannot be assigned”. We have to remove the assignment of “e” to a new exception object to solve this error. Read more at Java 7 multi-catch block.
Thats all for the java exception interview questions, I hope you will like them. I will be adding more to the list in the future, make sure you bookmark it for future use.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Thank You for the post pankaj, could you please update the indentation/numbering. Thank You.
- raja
May i know all these questions are enough for Interview
- Jai Kumar
Hi Sir, Thanks for advance, This is your statement, Java Exception handling framework is used to handle runtime errors only, compile time errors are not handled by exception handling framework. Could you please share me who will handle this compile time errors(compiletime exceptions).
- Ram
consider following code snipped try{ int a = 10/0; // statement 1 }catch(ArithmeticException ae){ // handle code } My question is – exception arise at statement 1 & Exception object created,but how java internally identify that exception is ArithmeticException only, not other one ?
- Chetan
Good set of questions Pankaj. Thanks for the effort you put in.
- Murali P
HI Pankaj, Thanks for providing this very useful tutorial, i learned a lot from it. It is mentioned that catching “NullpointerException” is perfectly fine. But i think it’s a bad practice to catch such Runtime Exceptions, they should be avoided with proper programming logics rather catching. what do you think? Thanks, -Dash
- Dash
Hi All, Question 5 ; One overriding rule w.r.t exception: If child class method throws any checked exception compulsory parent class method should throw the same checked exception or its parent. It needs not to exact same. But there are no restrictions for unchecked exceptions. The code will be fine like below… package com.journaldev.exceptions; import java.io.IOException; public class TestException4 { public void start() throws Exception{ } public void foo() throws NullPointerException{ } } class TestException5 extends TestException4{ public void start() throws IOException{ } public void foo() throws RuntimeException{ } } Thanks, Murali
- Murali Tekumatla
Please explain 5 question
- Shreya
Hi, First sample code in section 5 looked incorrect to me (catch(IOException | SQLException | Exception ex)). Types in multi-catch block must be disjoint. IO and SQL exceptions are subclasses of Exception in this case!
- Ozzybil
Beautiful tutorials.We love to study java from this tutorials all time!! Keep it Up!!
- Jitendra Singh