Top 40 Java Exception Handling Interview Questions With Answers

In this article, I am going to share Top 40 Java Exception Handling Interview Questions With Answers frequently asked on Interview. You can expect many questions from this topic in the interview.

Q1. What type of problem you can face while writing any java program?
Ans:
We can get two types of programs and they are as follows:

  • Error
  • Exception

Q2. What is an Error in Java programming?
Ans:
Error in Java programming indicates a serious problem or issue which can’t be handled by any try and catch block. Error terminates the program abnormally. Error is the subclass of java.lang.Throwable class. It is unchecked type and mostly time occurs at run time.

Q3. What are the types of Errors?
Ans: There are two types of errors and they are:

  • Compile type error
  • Run time error

Q4. What are Compile-type Errors?
Ans:
In the case of compile-time error, if any syntactical mistakes are there, then it is called as a compile-time error which will be identified at the time of compilation. Compile-time errors show that the compiler is inefficient to compile that specific program without correcting that.

Q5. What is Runtime error?
Ans:
The error which is being identified at runtime with the help of JVM is called runtime error. Runtime errors show the inefficiency of the JVM. For eg.

    • The main method is not available(compiler can compile without the main method).
    • If any stack memory-related problem is identified that will be represented by java.lang.StackOverflowError (memory required by the JVM to process).

Q6. What do understand by Exception?
Ans:
Some unexpected operation which occurs in a program is called as an exception.

Q7. What are the types of Exception are in Java?
Ans:
An exception is of two types:

    • Compile-time exception/checked exception
    • Runtime exception/Unchecked exception

Q8. Write a small java program which throws an exception?
Ans:

Class Xadmin {
 public static void main(String args[]) 
{ 
System.out.println(“in Xadmin”); 
int i=Integer.parseInt(arg[0]); 
int i1=10/i; 
System.out.println(i1);
 } 
}

Output

/* errors

  • java Xadmin (enter) If nothing is enteredin XadminException in thread “main”java.lang.ArrayIndexOutOfBoundsException: 0
  • java Xadmin abc (enter)in XadminException in thread “main”java.lang.NumberFormatException: For input string “abc”
  • java Xadmin 0 (enter)in XadminException in thread “main”

java.lang.ArithmeticException: 1 by Zero */

Q9. What will JVM do, if he encounters any problem?
Ans:
JVM will do the following things:

  • if any problem is identified, immediately control will be transferred to the JVM.
  • Now, JVM will identify the exact type of problem
  • After identifying the exact type of problem, it will create the object of that and will throw it to the program.
  • In the program, it will try to search matching catch block.
  • If the matching block is found, then the corresponding catch block will be processed.

Q10. How you will handle the exception with try and catch block?
Ans:
Handling exception by writing the  try and catch block:

  • Enclose that piece of code which you want to monitor, inside the try block.
  • Write the catch block associated with that try with the proper exception type.
  • By using a catch you can handle only one exception at a time.\
  • you can write multiple catch blocks associated with a try to handle the multiple types of exceptions.

Q11.  What are things you should keep in mind while writing try and catch?
Ans:
While writing  try and catch remember the following points:

  • There should not be any statement between try and catch.
  • There should not be any statement between catch and catch.
  • you can write try without any catch but you cannot write catch without any try.
  • When you are writing the catch blocks, the catch parameter should be sub to the supertype. It cannot have a parameter from super to subtype.

Q12. What is Finally Block?
Ans:

  • When any return statement is encountered, any other statements will not be processed after that. Immediately control will be transferred to the caller of the method.
  • In some cases, some statements are very important to be processed whether the return statement is processed or not.
  • For example, closing the resources. If you have used the resources and its not closed properly then it may create some problem. In order to make sure that the statement must be processed in any case in that you need to use the finally block.
  • When you are enclosing any statement inside the finally block then whether any return statement is encountered or not, any exception occurred or not, the finally block will always be processed.

Q13. In which case finally, the block will not execute?
Ans:
Finally block will not be processed only when System.exit() is used.

Q14. What are the things you should keep in mind while writing try, catch and finally block in java?
Ans:
Remember the following points while writing try, catch and finally.

  • There should not be any statement between try-catch-finally.
  • You can write try without a catch.
  • You should not write try-catch after finally.
  • You cannot write finally without a try.
  • Finally will be the last processing inside try-catch.

Q15. What JVM do internally when the return statement is encountered?
Ans: Whenever any return is encountered, the following things will be done internally by the JVM:

  • whenever any return statement is encountered, JVM checks whether any finally block is available or not.
  • If finally block is available then before transferring the control to the caller of the method, it will try to process the finally block and immediately after processing the finally block, control will be transferred to the caller of the method.

Q16. Can we write a return statement in try-catch-finally?
Ans:
Yes, but it has no benefit.
(if you are writing return statement in finally, then no need to write return in try and catch)
Sample code:

class Hello
{
int m1()
{
System.out.println(“m1 in Hello”);
try
{
int x=10/0;
return 10;
}
catch(Exception e)
{
e.printStackTrace();
return 20;
}
finally
{
System.out.println(“in finally”);
return 30;
}
}
}
public class Xadmin
{
public static void main(String args[])
{
Hello h1= new Hello();
int i= h1.m1();
System.out.println(i);
}
}

Q17. Can you write a java program to show to use of finally block?
Ans:

import com.sun.org.apache.reggexp.internal.recompile;
class Window
{
public Window()
{
System.out.println(“open window”);
}
public void close()
{
System.out.println(“close window”);
}
}
class Door
{
Door()
{
System.out.println(“open door”);
}
public void close()
{
System.out.println(“close door”);
}
}
class UseRes
{
int m1()
{
Door dr = null;
Window wn=null;
try
{
dr=new Door();
wn= new Windows();
System.out.println(“perform your task”);
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
dr.close();
wn.close();
}
return 20;
}
}
class Xadmin
{
public static void main(String args[])
{
UseRes ur = new UseRes();
ur.m1();
}
}

Q18. What is Autocloseable Interface?
Ans:
Autocloseable interface

  • if you want to develop your custom resources then write your resource class by implementing the AutoCloseable interface.
  • AutoCloseable interface has only one method, close() method.
  • This close() method must be overridden inside your class according to the resource requirement.
  • If you are using resource inside try with resource then your resource must implement AutoCloseable interface, otherwise, it will give the compile-time error.
  • If we are using try with resource and it is satisfying all the constraints then no use of writing any finally block, you can easily write it with that.

Q19. Write a java code for Autocloseable Interface?
Ans:

class Window implements AutoCloseable
{
public Window()
{
System.out.println(“open window”);
}
public void close()
{
System.out.println(“close window”);
}
}
class Door implements AutoCloseable
{
Door()
{
System.out.println(“open door”);
}
public void close()
{
System.out.println(“close door”);
}
}
public class Xadmin
{
public static void main(String args[])
{
try(Door dr= new Door();
Window wn=new Window() )
{
System.out.println(“use resource”);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

Q20. What is a Checked Exception or compile-time Exception?
Ans:

  • The exception being caught by the compiler at the time of compilation or caught by the compiler is called compile time exception.
  • Also, the exceptions which are the subclass of java.lang.Exception except for java.lang.RuntimeException is called compile time exception.

Q21. Tell the types of compile-time exception?
Ans:
The compile-time exception can be of two types:

  • User-defined
  • Built-in type

Q22. Is it compulsory to handle the compile-type exception?
Ans:
Compile time exception must be handled or reported either by writing try and catch or by propagating.

Q23. Can you tell an example of the compile-type exception?
Ans:
For example: java.lang.IOException, FileNOTFoundException, SQLException, JSPException.

Q24 What is Unchecked exception or Runtime exception?
Ans: Unchecked Exception or Runtime Exception:

  • The exceptions that are the subclass of java.lang.RuntimeException is called as Unchecked Exceptions.
  • These exceptions will be handled by JVM.

Q25 Is it compulsory to handle the runtime exception?
Ans: No, It need not be reported by writing try and catch or by propagating. Even if you want, you can handle it.

Q26. What are the types of Runtime exception?
Ans:
Runtime exceptions are also of two types:

    • User-defined
    • Built-in

Q27. What do you know about Built-in exception?
Ans:
The exception given by the technology vendors is called a built-in exception. These also can be checked and unchecked types
For example ServletException, JSPException, EJBException.

Q28. What is a User-Defined Exception?
Ans:
The exceptions that are being created by the developer according to the application requirement called as a user-defined exception.
For Example: InsufficientFoundException, AccountNumberDoesNotExist.

Q29. Tell the Steps to Write User Defined Exception?
Ans:

  • Write your exception class by extending java.lang.Exception or java.lang.RuntimeException.
  • Declare some instance variable inside exception class.
  • Write default constructor inside the exception class.
  • Write one parameterized constructor if required.
  • Override toString() method( it internally calls getMessage() method).
  • Override getMessage() method( it is available inside a throwable class and gives an exact reason of the exception).

Q30. Write the sample code for the User-Defined Exception:
Ans:

class InvalidAccNoException extends Exception
{
int accno;
public InvalidAccNoException()
{
}
InvalidAccNoException(int accno){
}
public String toString()
{
return “..”+getMessage();
}
public String getMessage()
{
return “..”;
}
}
class ServerNotRespondingException extends RuntimeException
{
}

public class Xadmin
{
public static void main(String args[])
{
try
{
int i=Integer.parseInt(args[0]);
}
catch(Exception e)
{
System.out.println(e);
}
}
}

Q31 What is “throw” keyword in Exception handing?
Ans:

  • The throw keyword is used to throw the exception form the body of the method.
  • If you are throwing any unchecked exception then there is no hard and fast rule that you will have to report about that exception using try and catch or by propagating.
  • But, it is always recommendable to handle the throw from the body of the method using try and catch.

Q32 What is the syntax of the throw keyword
Ans:

void m1()
{
ArthmeticException ae= new ArthmeticException();
throw ae;
}
or 
void m1()
{
throw new ArthmeticException();
}

If you are throwing any checked exception from the body of the method then you must have to report about that exception by writing try and catch or by propagating at method header.

Q33. What is “throws” keyword?
Ans:

  • throws keyword is used to throw the exception from the header of the method.
  • Whenever you are throwing any exception by writing throws keyword, it means you are directing caller of the method to report about the exception in it own way(i.e, either by using try and catch or by propagating).
  • If you are throwing any checked exception then the caller of the method must have to report about the exception by writing try and catch or by propagating.
  • If you are not doing that then it will give a compilation error.
  • If you are throwing an unchecked exception by writing throws keyword then you may or may not handle that.
  • If you are not handling it, it will automatically be handled by the JVM.

Q34. What is the syntax of the throws keyword?
Ans:

void m1() throws IOEXception
{
try
{
throw new IOException();
}
catch(Exception e)
{
//.....
}
}

Using both ‘throws’ and ‘throw’ will not give any compile-time error but the caller of m1() will have to report IOException by either using try and catch or by propagating.

Q35 when a super class method is throwing a method-level exception then what subclass overridden method should do?
Ans:

  • Subclass overridden method can ignore the exception which is being thrown from the superclass method as it is.
  • Subclass overridden method can report about the exception which is coming from the superclass as it is.
  • Subclass overridden method can report about the exception which is the subclass of the superclass method-level exception.
  • Subclass overridden method cannot report about the superclass of the superclass method-level exception.
  • Subclass overridden method cannot report about the new type of exception which is not coming from the superclass method.

Q36.what is printStackTrace()?
Ans:

  • it is available inside java.lang.Throwable
  • it is used to give the following three information about any exceptions:
    • type of exception
    • reason for exception
    • the line number of exception where it occurred.

Q37. What is getMessage()?
Ans:

  • it is available inside java.lang.Throwable
  • this is used to give an exact reason for the exception that why exactly it occurred.

Q38. What will happen to the Exception object after exception handling?
Ans:
Garbage collector will collect the exception object.

Q39. Difference between finally block and finalize?
Ans:
When any return statement is encountered, any other statements will not be processed after that. Immediately control will be transferred to the caller of the method. In some cases, some statements are very important to be processed whether the return statement is processed or not. Finalize is a method of the Object class. It is called by JVM just before an object is a garbage collected.

Q40. Which is the superclass of all types of errors and exceptions in java?
Ans:
Java.lang.Throwable is the superclass for all types of errors and exception in java

That’s all about Top 40 Java Exception Handling Interview Questions With Answers from Core Java Interviews. I have covered almost everything as per my knowledge for both freshers and experienced with 0 to 5 years, so prepare well for the Java interview Questions, I suggest you take a look on more Java Programming Interview Questions with answers on different topics of the core java posted in this xadmin website. Keep Learning!  All the Best!