Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconFull Stack Developmentbreadcumb forward arrow iconTop 30 Exception Handling Interview Questions and Answers [For Freshers & Experienced]

Top 30 Exception Handling Interview Questions and Answers [For Freshers & Experienced]

Last updated:
28th Aug, 2022
Views
Read Time
18 Mins
share image icon
In this article
Chevron in toc
View All
Top 30 Exception Handling Interview Questions and Answers [For Freshers & Experienced]

Exception handling is a concept that is implemented in algorithms to handle possible runtime errors, which may disrupt the normal flow of a program. Some of the errors which can be handled using this concept are:

  • ClassNotFoundException
  • IOException
  • SQLException
  • RemoteException
  • RuntimeException:
    • ArithmeticException 
    • NullPointerException
    • NumberFormatException
    • IndexOutOfBoundsException
      • ArrayIndexOutOfBoundsException
      • StringIndexOutOfBoundsException

The merit of this implementation is to prevent a crash of the program if there is an exception while executing the program. Without Exception Handling, the program will throw an error when it encounters an exception, and the rest of the program will not be executed. However, implementing this concept will give a workaround in which the rest of the program is executed if they are independent with respect to the exception incurred. To learn more, check out our data science courses.

Check out our free courses to get an edge over the competition.

In order to understand the regularity of interview questions on exception handling in Java, one has to understand the importance the topic carries. 

Ads of upGrad blog

Check Out upGrad’s Full Stack Development Bootcamp

Minute errors from the developer’s side can significantly hamper the flow of data. For example, if there are 8 statements in a row, and the fourth statement has any error, all the statements after that will not be executed. However, if exception handling is implemented, all the other statements will be executed except for the one with an error. This is why knowing and using exception handling is so important. 

Check Out upGrad’s Python Bootcamp

Some of the main keywords that are important in learning exception handling in Java include:

KeywordDescription
TRYThis keyword is implemented when specifying a block, therefore, where should one place an exception code. This keyword can not be implemented alone and needs to be followed by either FINALLY or CATCH.
CATCHThis keyword is used to determine what to do with the exception. Before this, the TRY block must be used. 
THROWThis keyword is used to throw an exception
FINALLYThis block is used to execute the necessary code for the program.

There are multiple reasons behind the occurrence of exceptions, some of which are: invalid user input, losing network connection, coding errors, disk running out of memory, any kind of device failure, etc. therefore, the chances of occurring errors or exceptions are quite high, which is why Java exception handling interview questions are pretty common in any developer job. So, make sure to prepare for these Java exception handling interview questions by clarifying concepts.

As a topic, getting exception handling in java interview questions is quite common, which makes it even more important to prepare. The exception handling in java interview questions helps the recruiter to understand the depth of knowledge of a candidate and see whether or not they can prevent and handle any undesired situation, such as crashing a program or failing requests

Below is a list of interview questions on exception handling in Java that can help anyone crack their dream interview. 

Read: Must Read 30 Selenium Interview Questions & Answers: Ultimate Guide

Exception Handling Interview Questions and Answers

1. What do you mean by an exception?

It is an abnormal condition that is sometimes encountered when a program is executed. It disrupts the normal flow of the program. It is necessary to handle this exception; otherwise,it can cause the program to be terminated abruptly.

2. Explain how exceptions can be handled in Java. What is the exception handling mechanism behind the process?

There are three parts to the exception handling mechanism. These are called:

  • Try block: The section of the code which is first attempted to be executed and monitored for any exception that might occur. 
  • Catch block: If any exception is thrown by the ‘try’ block, it is caught by this code section. 
  • Finally block: Code under this section is always executed irrespective of exceptions caught in ‘try’ block, if any. Even if there is no exception, the code under this block will be executed. 

Explore our Popular Software Engineering Courses

3. Is it possible to keep other statements in between ‘try’, ‘catch’, and ‘finally’ blocks?

It is not recommended to include any statements between the sections of  ‘try’, ‘catch’, and ‘finally’ blocks, since they form one whole unit of the exception handling mechanism. 

try

{

    //Code which is monitored for exceptions.

}

//You can’t keep statements here

catch(Exception ex)

{

    //Catch the exceptions thrown by try block, if any.

}

//You can’t keep statements here

finally

{

    //This block is always executed irrespective of exceptions.

}

4. Will it be possible to only include a ‘try’ block without the ‘catch’ and ‘finally’ blocks?

This would give a compilation error. It is necessary for the ‘try’ block to be followed with either a ‘catch’ block or a ‘finally’ block, if not both. Either one of ‘catch’ or ‘finally’ blocks is needed so that the flow of exception handling is undisrupted. 

In-Demand Software Development Skills

5. Will it be possible to keep the statements after the ‘finally’ block if the control is returning from the finally block itself?

This will result in an unreachable catch block error. This is because the control will be returning from the ‘finally’ block itself. The compiler will fail to execute the code after the line with the exception. That is why the execution will show an unreachable code error. 

Dreaming to Study Abroad? Here is the Right program for you

6. Explain an unreachable catch block error.

In the case of multiple catch blocks, the order in which catch blocks are placed is from the most specific to the most general ones. That is, the sub classes of an exception should come first, and then the super classes will follow. In case that the super classes are kept first, followed by the sub classes after it, the compiler will show an unreachable catch block error.

public class ExceptionHandling

{

    public static void main(String[] args)

    {

        try

        {

            int i = Integer.parseInt(“test”);   

//This statement will throw a NumberFormatException //because the given input is string, while the //specified format is integer. 

        }

        catch(Exception ex)

        {

System.out.println(“This block handles all exception types”);

//All kinds of exceptions can be handled in this //block since it is a super class of exceptions.

        }

        catch(NumberFormatException ex)

        {

            //This will give compile time error

            //This block will become unreachable as the

//exception would be already caught by the above //catch block

        }

    }

}

Explore Our Software Development Free Courses

7. Consider three statements in a ‘try’ block: statement1, statement2, and statement3. It is followed by a ‘catch’ block to catch the exceptions that occurred during the execution of the ‘try’ block. Assume that the exception is thrown at statement2. Do you think the statement3 will be executed?  

Statement3 will not be executed. If an exception is thrown by the ‘try’ block at any point, the remaining code after the exception will not be executed. Instead, the flow control will directly come to the ‘catch’ block. 

8. Differentiate error and exception in Java.

The key difference between error and exception is that while the error is caused by the environment in which the JVM(Java Virtual Machine) is running, exceptions are caused by the program itself. For example, OutOfMemory is an error that occurs when the JVM exhausts its memory.

But, NullPointerException is an exception that is encountered when the program tries to access a null object. Recovering from an error is not possible. Hence, the only solution to an error is to terminate the execution. However, it is possible to workaround exceptions using try and catch blocks or by throwing exceptions back to the caller function.

Must Read: Java Interview Questions & Answers

9. What are the types of exceptions? Explain them.

There are two types of exceptions: 

Checked Exceptions

The type of exceptions that are known and recognized by the compiler. These exceptions can be checked in compile time only. Therefore, they are also called compile time exceptions. These can be handled by either using try and catch blocks or by using a throw clause. If these exceptions are not handled appropriately, they will produce compile time errors. Examples include the subclasses of java.lang.Exception except for the RunTimeException.

Unchecked Exceptions

The type of exceptions that are not recognized by the compiler. They occur at run time only. Hence, they are also called run time exceptions. They are not checked at compile time. Hence, even after a successful compilation, they can cause the program to terminate prematurely if not handled appropriately. Examples include the subclasses of java.lang.RunTimeException and java.lang.Error.

Learn Software Engineering Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

10. What is the hierarchy of exceptions in Java?

The java.lang.Throwable is a super class of all errors and exceptions in Java. This class extends the java.lang.Object class. The argument of catch block should be its type or its sub class type only. The Throwable class includes two sub classes:

  1. java.lang.Error : This is a super class for all error types in Java. Common errors included under this are – 
    1. java.lang.VirtualMachineError: Under this –
      1. StackOverFlowError
      2. OutOfMemoryError
    2. java.lang.AssertionError
    3. java.lang.LinkageError: Under this – 
      1. NoClassDefFoundError
      2. IncompatibleClassChangeError
  2. java.lang.Exception: This is a super class of all exception types in Java. Common exceptions under this are – 
    1. RunTimeException
      1. ArithmeticException
      2. NumberFormatException
      3. NullPointerException
      4. ArrayIndexOutOfBoundsException
      5. ClassCastException
    2. java.lang.InterruptedException
    3. java.lang.IOException
    4. java.lang.SQLException
    5. java.lang.ParseException

11. What are runtime exceptions in Java? Give a few examples. 

The exceptions that occur at run time are called run time exceptions. The compiler cannot recognise these exceptions, like unchecked exceptions. It includes all sub classes of java.lang.RunTimeException and java.lang.Error. Examples include, NumberFormatException, NullPointerException, ClassCastException, ArrayIndexOutOfBoundException, StackOverflowError etc.

upGrad’s Exclusive Software and Tech Webinar for you –

SAAS Business – What is So Different?

 

12. Define OutOfMemoryError in Java.

It is the sub class of java.lang.Error which is encountered when the JVM runs out of memory.

13. Differentiate between NoClassDefFoundError and ClassNotFoundException in Java.

Both NoClassDefFoundError and ClassNotFoundException occur when a particular class is not found in run time. However, they occur under different scenarios. NoClassDefFoundError is when an error occurs because a particular class was present at compile time but it was missing at run time. ClassNotFoundException occurs when an exception is encountered for an application trying to load a class at run time which is not updated in the classpath.

Exception handling tricky questions:

Apart from straightforward Java exception handeling interview questions one might also have to deal with a number of exception handling tricky questions. Below are examples of such.  

14. Does the ‘finally’ block get executed if either of ‘try’ or ‘catch’ blocks return the control?

The ‘finally’ block is always executed irrespective of whether try or catch blocks are returning the control or not.

15. Is it possible to throw an exception manually? If yes, explain how.

It is possible to throw an exception manually. It is done using the ‘throw’ keyword. The syntax for throwing an exception manually is

throw InstanceOfThrowableType;

Here is an example of using the ‘throw’ keyword to throw an exception manually.

try

{

    NumberFormatException ex = new NumberFormatException(); //Here we create an object for NumberFormatException explicitly

    throw ex; //throwing NumberFormatException object explicitly using throw keyword

}

catch(NumberFormatException ex)

{

    System.out.println(“In this block, the explicitly thrown NumberFormatException object can be caught.”);

}

Read: Top 35 Spring Interview Questions & Answers: Ultimate Guide

16. What do you mean by rethrowing an exception in Java?

The exceptions which are raised in the ‘try’ block are handled in the ‘catch’ block. If the ‘catch’ block is unable to handle that exception, it is possible that it can rethrow the same exception using the ‘throw’ keyword. This mechanism is called rethrowing an exception. The implementation is as follows: 

try

{

    String s = null;

    System.out.println(s.length()); //This statement throws a NullPointerException

}

catch(NullPointerException ex)

{

    System.out.println(“Here the NullPointerException is caught”);

    throw ex; //Rethrowing the NullPointerException

}

17. Why do you use the ‘throws’ keyword in Java?

If it is possible for a method to throw an exception if it could not be handled, it should specify that exception using the ‘throws’ keyword. It will be helpful to the caller functions of that method in handling that exception. The syntax for using the ‘throws’ keyword is,

return_type method_name(parameter_list) throws exception_list

{

     //code

}

Here, exception_list is the list of exceptions which may be thrown by the method. These exceptions should be separated by commas. An example of the code : 

public class ExceptionHandling

{

    public static void main(String[] args)

    {

        try

        {

            methodWithThrows();

        }

        catch(NullPointerException ex)

        {

            System.out.println("NullPointerException thrown by methodWithThrows() method will be caught here");

        }

    }

 

    static void methodWithThrows() throws NullPointerException

    {

        String s = null;

        System.out.println(s.length()); //This statement throws NullPointerException

    }

}

18. It is often recommended to keep clean up operations like closing the DB resources inside the ‘finally’ block. Why is it necessary? 

The ‘finally’ block is always executed irrespective of the fact if exceptions are raised in the ‘try’ block or if the raised exceptions are caught in the ‘catch’ block or not. Keeping the clean up operations in ‘finally’ block ensures the operation of these operations in any case, and will not be affected by exceptions, which may or may not rise. 

19. How would you differentiate between final, finally and finalize in Java?

First, ‘final’ is a keyword that can be used to make a variable or a method or a class as unchangeable. To put it simply, if a variable is declared as final, once it is initialized, its value can not be altered. If a method is declared as final, it cannot be overridden or modified in the sub class. If a class is declared as final, it cannot be extended into further classes. 

Second, ‘finally’ is a block which is used in exception handling along with the ‘try’ and ‘catch’ blocks. This block is always executed irrespective of a raised exception or if the raised exception is handled. Usually, this block is used to perform clean up operations to close the resources like database connection, I/O resources, etc.

Third, the finalize() method is a protected method. It belongs to java.lang.Object class. Every class created in Java inherits this method. The garbage collector thread calls this method before an object is removed from the memory. Before an object is removed from the memory, this method is used to perform some of the clean-up operations.

protected void finalize() throws Throwable

{

    //Clean up operations

}

20. What are customized exceptions in java?

Exception classes can be thrown in Java as per the requirements of the program flow. These exceptions are called user-defined exceptions. They are also called customized exceptions. These exceptions must extend any one of the classes in the exceptions’ hierarchy. 

21. How would you explain a ClassCastException in Java?

When the JVM is unable to cast an object of one type to another type, this exception is raised. It is a RunTimeException.

22. Differentiate between throw, throws and throwable in Java.

First, the keyword ‘throw’ is used to throw an exception manually in Java. Using this keyword, it is possible to throw an exception from any method or block. However, it is essential that the exception must be of type java.lang.Throwable class or it belongs to one of the sub classes of java.lang.Throwable class. 

Second, the keyword ‘throws’ is used in the method signature in Java. If the method is capable of throwing exceptions, it is indicated by this method. The mentioned exceptions are handled by their respective caller functions. It is done either by using try and catch blocks or by using the throws keyword. 

Third, the super class for all types of errors and exceptions in Java is called Throwable. It is a member of the java.lang package. The JVM or the throw statement raises only instances of this class or its subclasses. The catch block should contain only one argument and it should be of this type or its subclasses. In case customized exceptions are created, they should extend this class too. 

23. Explain the StackOverflowError in Java.

This is an error that is thrown by the JVM when the stack overflows in runtime.

24. Is it possible to override a super class method that throws an unchecked exception with checked exceptions in the sub class?

It is not possible because if a super class method throws an unchecked exception, it will be overridden in the sub class with the same exception or any other unchecked exceptions. But, it can not be overridden with checked exceptions.

25. Define chained exceptions in Java.

In a program, one exception can throw many exceptions by inducing a domino effect. This causes a chain of exceptions. It is beneficial to know the location of the actual cause of the exception. This is possible with the chained exceptions feature in Java. This has been introduced since JDK 1.4. For implementation of chained exceptions in Java, two new constructors and two new methods are included in the Throwable class. These are,

Constructors Of Throwable class:

    1. Throwable(Throwable cause): The cause is the exception that raises the current exception.
    2. Throwable(String msg, Throwable cause): The msg string is the exception message. The exception that raises the current exception is the cause here.

Methods Of Throwable class:

    1. getCause() method : The real cause of a raised exception is returned by this method.
    2. initCause(Throwable cause) method : The cause of the calling exception is set by this method.  

26. Which class is defined as a super class for all types of errors and exceptions in Java?

The super class for all types of errors and exceptions is java.lang.Throwable in Java.

27. What can classify as a correct combination of try, catch and finally blocks?

A combination of try and catch block.

try

{

    //try block

}

catch(Exception ex)

{

    //catch block

}

A combination of try and finally block. 

try

{

    //try block

}

finally

{

    //finally block

}

A combination of all three: try, block, finally blocks. 

try

{

    //try block

}

catch(Exception ex)

{

    //catch block

}

finally

{

    //finally block

}

28. Why do you use printStackTrace() method?

This method is used to print detailed information about the exception that occurred.

29. What are some examples of checked exceptions?

Some examples of checked exceptions include ClassNotFoundException, SQLException, and IOException.

30. What are some examples of unchecked exceptions?

Some examples of unchecked exceptions include NullPointerException, ArrayIndexOutOfBoundsException and NumberFormatException.

Read our Popular Articles related to Software Development

Also Read: Must Read 47 OOPS Interview Questions & Answers For Freshers & Experienced

How to prepare for the interview?

In order to maximize your chances of being shortlisted, you need to prepare well beforehand for the interviews. Often times candidates even get rejected in their final interview round, so preparing for them will be a wiser choice. Here are some tips and advice you can make use of to better your interview preparations. 

  1. Get information regarding the interview format. There are a handful of formats that a recruiter can use in their interview process. It can be quizzes, online coding assignments,  take-home assignments or even telephonic or video-called interviews. Quizzes and assignments are often thrown at the very early stage of the interview to test the candidate’s basic technical knowledge. Interviews over call and video calls are most common and usually are held for the shortlisted candidates where the interviewer would give a problem to the candidate to solve live on various apps like CoderPad, CodePen or even Google docs. Therefore getting familiar with these platforms beforehand can be advantageous and less chaotic. 
  2. Picking a programming language and mastering it. It is not beneficial to be a jack of all trends and a master of none. Hence, choosing a specific programming language and gaining in-depth knowledge of it is always a better choice. In this manner, one can always master programming languages one by one as well. 
Ads of upGrad blog

The most popular programming languages for coding interviews are Python, Java and C++. Try and contribute a few weeks at least to each of the languages one by one. However, if the interview is knocking on the door, focusing on the one language in which the candidate has the highest proficiency, would be better rather than learning an entirely new language at the last moment. 

  1. Go through coding interviews and look for the pattern. There are some generic questions that are asked in the majority of the coding interviews. Do not skip them. There are a handful of platforms that can be used for interview preparations such as LeetCode, CodeForces etc. 
  2. Make a study plan. As tedious as it may sound but it is the truth. Staying consistent is crucial for reaching any goal. Try and make a study plan where at least 2-3 hours daily are kept aside for repairing for the interview. 

Wrapping up

If you’re interested to learn more about big data, check out upGrad & IIIT-B’s PG Diploma in Full-stack Software Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.

If you are interested in learning Data Science and opt for a career in this field, check out IIIT-B & upGrad’s Executive PG Programme in Data Science which is created for working professionals and offers 10+ case studies & projects, practical hands-on workshops, mentorship with industry experts, 1-on-1 with industry mentors, 400+ hours of learning and job assistance with top firms.

Profile

Rohan Vats

Blog Author
Software Engineering Manager @ upGrad. Passionate about building large scale web apps with delightful experiences. In pursuit of transforming engineers into leaders.

Frequently Asked Questions (FAQs)

1Which is the best programming language for database management?

There is no conclusive answer to this topic because it depends on your organization's specific demands. SQL, Java, and Python are some of the most common database management languages. SQL is a database management language that is simple to learn and use. It also offers a lot of features that let you several different things. Java is a sophisticated programming language that can be used to build database management systems that are both robust and dependable. It has a vast user base and a large developer community that may assist you with your development efforts. Python is a flexible programming language that can be used for a wide range of tasks, including database management. It has a variety of characteristics that make it ideal for this job, including ease of use, readability, and adaptability. Python also has a big community of users and developers who can help with database management by providing support and resources.

2Should I Become an A.I. developer or a web developer?

There is no one-size-fits-all solution to this question because the optimal choice for you will be determined by your unique abilities and interests. If you love to work with complex algorithms, though, you should work as an A.I. developer. If you want to build websites and web apps, on the other hand, you should become a web developer.

3How can I use Ruby for A.I. development?

Ruby is a programming language that allows programmers to write clean, concise code for a wide range of applications. It has an easy-to-read and grasp syntax, making it a popular choice for both novices and experienced programmers. Ruby also has a wealth of features and capabilities, making it a versatile platform for developing complex applications. Depending on the project, the optimal technique to use Ruby for A.I. development may differ. However, popular uses of Ruby for A.I. development include natural language processing, machine learning, and data analysis.

Explore Free Courses

Suggested Blogs

Top 40 MySQL Interview Questions & Answers For Beginners & Experienced [2023]
117647
Have a Data engineering or data science interview coming up? Need to practice some of the most asked MySQL interview questions? The article compiles t
Read More

by Rohan Vats

07 Nov 2023

Literals In Java: Types of Literals in Java [With Examples]
5885
Summary: In this article, you will learn about Literals in Java. Literals in Java Integral Literals Floating-Point Literals Char Literals String Lit
Read More

by Rohan Vats

29 Oct 2023

10 Interesting HTML Project Ideas & Topics For Beginners [2023]
392247
Summary In this article, you will learn 10 Interesting HTML Project Topics. Take a glimpse below. A tribute page A survey form Technical documentati
Read More

by Rohan Vats

04 Oct 2023

15 Exciting SQL Project Ideas & Topics For Beginners [2023]
284692
Summary: In this Article, you will learn 15 exciting SQL project ideas & topics for beginners. Library Management System Centralized College Dat
Read More

by Rohan Vats

24 Sep 2023

17 Interesting Java Project Ideas & Topics For Beginners 2023 [Latest]
34383
Summary: In this article, you will learn the 17 Interesting Java Project Ideas & Topics. Take a glimpse below. Airline reservation system Data v
Read More

by Rohan Vats

24 Sep 2023

9 Exciting Software Testing Projects & Topics For Beginners [2023]
8161
Software testing might constitute 50% of a software development budget but it is viewed as a lethargic and unnecessary step by most students. Even edu
Read More

by Rohan Vats

21 Sep 2023

Top 10 Skills to Become a Full-Stack Developer in 2023
218064
In the modern world, if we talk about professional versatility, there’s no one better than a Full Stack Developer to represent the term “versatile.” W
Read More

by Rohan Vats

21 Sep 2023

Java Free Online Course with Certification [2023]
56887
The PYPL Popularity of Programming Language Index maintains that Java is the second most popular programming language in the world, after Python.  Alt
Read More

by Rohan Vats

20 Sep 2023

Salesforce Developer Salary in India in 2023 [For Freshers & Experienced]
903143
Wondering what is the range of salesforce salary in India? Businesses thrive because of customers. It does not matter whether the operations are B2B
Read More

by Rohan Vats

20 Sep 2023

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon