Java Exception Handling Interview Questions and Answers (2024)

If you are not handle the Exception in Program that means at the same line program flow will stop.So risky or logic code contains into Try block , handle code contains into Catch block and if exception not handle than we use Finally block.


Here, we have listed the most important exception handling interview questions in Java with the best possible answers for 2024.

These interviewer can ask you different questions, Like as: java exception handling or what is java exception handling or Java Exception Handling Interview Questions or types of exception handling in java, extra…

Java Exception Handling

1). What is Exception in Java?                                 (Most Imp Question) 


Exception is unexcepted, unwanted or abnormal situation accoured at run time that is Exception.


Note: If an exception is not handled, the program abruptly terminates.


Example:

   public class Exception_Demo {

public static void main(String[] args) {

try {

int a = 10 / 0;

} catch (Exception e) {

System.out.println(” Exception is handle by catch block “);

}

System.out.println(“it means main mehtod is running and Program is running at last line”);

}}



2). What is the super or base class of all exceptions in Java?


Exception is the superclass of all exceptions in Java.


3). What is the top most class for error and exception classes in Java?                 (Most Imp Question) 


Throwable is the superclass for error and exception classes in Java.


4).  What is Exception handling in Java?                                                                       ( Imp Question) 


To maintain the normal flow of the program orapplication is called exception handling. 

It is a powerful mechanism to handle runtime exception, Like as: ClassNotFoundException, FileNotFoundException, IOException, etc.



5). What are the differences between Error and Exception in java?                            (Most Imp Question) 


Main differences between Error and Exception are :


Errors are caused by the JVM environment in which the application is running. Example: OutOfMemoryError while Exceptions are caused by the application itself. Example: NullPointerException.


Errors can only occur at runtime while Exceptions can occur at compile time or runtime.



6). How the exceptions are handled in java?                                           (Imp Question) 


Exceptions handling can be done using try, catch and finally blocks.


try : The risky code or set of statements that may raise exception should be try block.


catch : This block catches the exceptions thrown in the try block.


finally : This block of code is always executed whether an exception has occurred in the try block or not except in one scenario explained in below question.



7). Is finally block always get executed in the java program?                              (Imp Question)


By using System.exit(0) in the try or catch block, results in finally block does not execute. The reason is System.exit(0) line terminates the running java virtual machine. Termination leads to no more execution of the program.



8).What is the advantage of using exception handling in Java?


The main advantage of exception handling to maintain the normal flow of the program:


It provides flexibility in handling situations of errors.

It allows us to define a user-friendly message to handle the exception.

It helps to separate “Error-Handling code” from “Regular code.”



9). What is Checked & Unckckec exception? or types of exception in java ?                         (Most Imp Question)


 or Difference between Checked and Unchecked Exceptions ?

 

I) Checked ExceptionThe classes that directly inherit the Throwable class except RuntimeException and Error are known as checked exceptions. For example, IOException, SQLException, etc. 


Note: Checked exceptions are checked at compile-time.


II) Unchecked ExceptionThe classes that inherit the RuntimeException are known as unchecked exceptions. 

For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. 


Note: Unchecked exceptions are not checked at compile-time, but they are checked at runtime




10). What is the difference between final, finally and finalize in java?                      (Most Imp Question)


final keyword:


By declaring a variable as final, the value of final variable cannot be changed.

By declaring a method as final, method cannot be overridden.

By declaring a class as final, class cannot be extended.


finally:

Used after try or try-catch block, will get executed after the try and catch blocks without considering whether an exception is thrown or not.


finalize:

Finalize method is the method that Garbage Collector always calls just before the deletion/destroying the object which is no longer in use in the code.



11).Can we throw an exception manually/explicitly?                                               (Imp Question)


Yes, using throw keyword we can throw an exception manually.


Syntax throw InstanceOfThrowableType;



12) What is types of Exception in java ? Different type of scenarios of Exception.                         (Most Imp Question)


There are given some scenarios where unchecked exceptions may occur. 


I) Arithmetic-Exception: If we divide any number by zero, there occurs an ArithmeticException.


Example  int a=50/0;   //ArithmeticException 

 

II) NullPointer-Exception: If we have a null value in any variable, performing any operation on the variable throws NullPointerException.


Example  String s=null;  

                   System.out.println(s.length());//NullPointerException  


III). Number-Format: Exception:If the formatting of any variable or number is mismatched, it may result into NumberFormatException. Suppose we have a string variable that has characters; converting this variable into digit will cause NumberFormatException.


Example:   String s=”abc”;  

                   int i=Integer.parseInt(s);//NumberFormatException  

   


Different between  ClassNotfoundException and NoClassDefFoundError.                               (Most Imp Question)    


IV). ClassNotFoundException: It is checked exception and when JVM want to load class at compile time but not find out, this is konw as ClassNotfoundException.                                                           

 

V). NoClassDefFoundError: It is unchecked exception and when JVM load the class file then compile time it is available but run time not find out.                                                                            

   



VI). IO Exception: when input/output operation has failed

    

Example:

     try {

         FileInputStream inputStream = new FileInputStream(“file.txt”);

              } 

         catch (IOException e) {

         System.out.println(“An I/O error has occurred: ” + e.getMessage()); }



VII). SQLException: it is a checked exception in Java that signals that an error has occurred while working with a relational database.

   


VIII).VirtualMachineError: it is a type of error that occurs when the Java Virtual Machine (JVM) is unable to allocate memory for a new object


Example:

         try {

         while (true) {

         // Allocating a large amount of memory

         byte[] bytes = new byte[1024 * 1024 * 1024];

         }

         } catch (OutOfMemoryError e) {}



IX). StackOverflowError: it is thrown when the call stack of a program grows too large, meaning there is an excessive number of nested method calls. This can occur when there is an infinite loop of method calls or a deep recursion. 


Example:

try {

  deepRecursion(0);

} catch (StackOverflowError e) {}



X). OutOfMemoryError: it  is thrown when the Java Virtual Machine (JVM) is unable to allocate memory for a new object.


Example:

try {

a large amount of memory

byte[] bytes = new byte[1024 * 1024 * 1024];

  }   } catch (OutOfMemoryError e) {}

  




13). What are the keywords in Java for Exception Handling?                                                (Imp Question)

throw, throws, try, catch and finally



14). What is Custom Exception in Java?                                                                                    (Most Imp Question)

Creating our own Exception is known as custom exception. By creating the custom exception, we can have your own exception and message.

Reasons to use custom exceptions:

Business logic exceptions: These are the exceptions related to business logic and workflow. It is useful for the application users or the developers to understand the exact problem.


Example:

    //A Class that represents use-defined exception

class MyException extends Exception {

public MyException(String s)

{

// Call constructor of parent Exception

super(s);

}}

//A Class that uses above MyException

public class Custom_exception {

// Driver Program

public static void main(String args[])

{

try {

// Throw an object of user defined exception

throw new MyException(“Eception is that our Business logic fail at the time checking accoutn detials”);

}

catch (MyException ex) {

System.out.println(“this exception Caught”);

// Print the message from MyException object

System.out.println(ex.getMessage());

}}}