Sunday, April 9, 2023

Exception Handling In Java Interview Questions : 2023

Exception handling is an essential feature of Java that enables programmers to manage and recover from unexpected errors that occur during program execution. It helps in maintaining the stability and robustness of the application by providing a mechanism to deal with errors and exceptions.In this article, we will discuss some of the commonly asked interview questions related to exception handling in Java.


Exception Handling In Java Interview Questions


Exception Handling In Java Interview Questions 


1. What is Exception?

An unwanted event that disturbs normal execution flow of the program is called Exception.

2.What is Exception Handling?

The mechanism of handling unexpected errors in a java program is called exception handling.

3.Explain Exception hierarchy.

Exception hierarchy



At the top of the hierarchy is the "Throwable" class, which is the base class for all exceptions and errors in Java. The "Throwable" class has two subclasses: "Exception" and "Error".

"Exception" class represents exceptional conditions that can be caught and handled by a program. It has several subclasses, such as "IOException", "ClassNotFoundException", and "RuntimeException".

"IOException" is an exception that occurs when there is an error while performing input/output operations. "ClassNotFoundException" is an exception that occurs when a class cannot be found. "RuntimeException" is a subclass of "Exception" that represents exceptions that occur during the runtime of a program, such as "NullPointerException" or "ArrayIndexOutOfBoundsException".

"Error" class represents exceptional conditions that are not expected to be caught or handled by a program. It has several subclasses, such as "OutOfMemoryError" and "StackOverflowError". These exceptions typically indicate serious problems that cannot be recovered from and should be allowed to crash the program.

Overall, the exception hierarchy in Java provides a way for developers to categorize and handle exceptions in a structured and organized manner.

4.Difference Between Error And Exception.

Error

Exception

Error occurs outside of our programmatic control. Exception occurs due to bug/defect in our program.
Error Not recoverable. Exceptions are Recoverable.
ex. out of memory error. ex. ArithmaticException, ArrayIndexedOutOfBoundException.

5.Diffrence between Checked And Unchecked Exception.

Checked Exception

Unchecked Exception

Occurs at Compile time. Occurs at a Runtime.
Compiler will force to handle this exception through either try, catch blocks or throws. It is programmers responsibility to take care of unchecked exceptions.
ex. IOException, FileNotFoundException. ex. NullPointerException, ArrayIndexedOutOfBoundException.

6.How Exception handling can be done in Java?

1.Using try, catch, finally Block:

Try Block: Enclose the code that might generate an exception within a try block. If an exception is thrown within this block, it is caught by the catch block.

Catch Block: Define a catch block to handle the exception. The catch block should contain the code that handles the exception. It is executed when an exception is thrown in the corresponding try block.

Finally Block: Optionally, you can define a finally block. The code in this block is executed regardless of whether an exception is thrown or not.

Example:



try
// code that might throw an exception int a = 5/0
} catch (ArithmeticException e) { 
// exception handling code 
 System.out.println("An arithmetic exception occurred: " + e.getMessage()); 
} finally
// finally block code 
 System.out.println("Finally block is executed"); 
}

In the above code, the try block attempts to divide the integer 5 by 0, which results in an ArithmeticException. The catch block catches the exception and prints a message. The finally block is executed after the try/catch block, regardless of whether an exception is thrown or not.

2.Using throws keyword:

The throws keyword to declare that a method may throw a specific exception. This keyword is used in the method signature to indicate that the method might throw an exception, but the actual exception handling is delegated to the caller of the method.

 Example :



public void myMethod() throws MyException
// code that might throw MyException 
if(someCondition) { 
throw new MyException("An error occurred"); 
 }
 }


In the above code, the myMethod() method might throw a MyException exception. The throws keyword is used in the method signature to declare that this method may throw this specific exception.

7.What are the Possibility of try catch finally blocks?

  1. try, catch, finally ===> Valid.
  2. try, catch, catch ===> Valid (multiple catch blocks valid).
  3. try, finally ===> Valid (without catch block it will be abnormal termination, but through finally we can close resources. so it is Valid).
  4. only try block ===> Not Valid (catch or finally block is required with try block).
  5. only catch block ===> Not Valid (try block is required with catch block).
  6. only finally block ===> Not Valid (try block is required with finally block).

8.Diffrence Between Throw and Throws keyword.

Throw

Throws

The throw keyword is used to throw an exception explicitly. The throws keyword is used to declare an exception.
It is used in try block or inside the method. It is use with method signature.
Only single exception is thrown by using throw. Multiple exception can be thrown by using throws.
The instance variable follows the throw keyword. The exception class names follow the throws keyword.

9.Does finally block get executed if either try or catch blocks are returning the control?

  1. Yes, finally block will be always executed as it is mainly used to closed the open resources.
  2. Except System.exit() or System crashes.(it means if we write System.exit at that time finally block not executed).

10.What is the use of printStackTrace() method?

It is used to print the detailed information about the exception occurred.

Example:



public class Example
public static void main(String[] args)
try { int[] numbers = new int[3]; 
 numbers[4] = 5
// This will throw an ArrayIndexOutOfBoundsException 
 } catch (ArrayIndexOutOfBoundsException e) { 
 e.printStackTrace(); 
 } 
 } 
}

In this example, we create an array of integers with a length of 3, and then attempt to access the element at index 4, which is outside the bounds of the array. This will throw an ArrayIndexOutOfBoundsException.

We catch the exception using a try-catch block, and then call the printStackTrace() method on the exception object. This will print the following stack trace to the console:



java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 3 at Example.main(Example.java:5)

The stack trace shows that the exception occurred in the main method of the Example class, on line 5. It also shows that the exception is an ArrayIndexOutOfBoundsException, and provides a message indicating the index that was out of bounds. This information can be very helpful in identifying and fixing the problem in the code.

11.How to create custom exception in Java?

  1. Create a new class whose should end with an Exception.
  2. Make the class extends Exception.
  3. Create a constructor with a String parameter.
  4. In the constructor, call the super constructor and pass the message.

Example:



public class MyException extends Exception
public MyException() {} 
public MyException(String message) { super(message); } 
public MyException(Throwable cause) { super(cause); } 
public MyException(String message, Throwable cause) { super(message, cause); } 
}

  1. The first constructor takes no arguments and simply calls the superclass constructor.
  2. The second constructor takes a message argument and passes it to the superclass constructor.
  3. The third constructor takes a Throwable cause argument and passes it to the superclass constructor.
  4. The fourth constructor takes both a message and a cause argument and passes them to the superclass constructor.


public class Example
public static void main(String[] args) throws MyException { 
try
// Some code that might throw an exception 
throw new MyException("This is a custom exception"); 
 } catch (MyException e) { 
 System.out.println("Caught exception: " + e.getMessage());
 e.printStackTrace(); 
 } 
 } 
}

In this example, we create a MyException object and throw it using the throw keyword. We catch the exception using a try-catch block, and then print the exception message and stack trace using the getMessage() and printStackTrace() methods, respectively.

Output:



Caught exception: This is a custom exception MyException: This is a custom exception at Example.main(Example.java:5)

This code creates a new instance of MyException and throws it. The catch block catches the exception and prints the message and stack trace to the console.

12. What is Difference Between final, finally and finalize ?

final, finally and finalize


13.Rules for Method Overriding in Exception handling.

1. Checked Exception :

If parent class throws checked exceptions, then child class should throw that exception/or its subtype exception.

2. Unchecked Exception :

But no restriction for unchecked exception. Both classes are independent.

Conclusion:

Exception handling is a crucial technique in programming that enables developers to handle abnormal errors or failures that may occur during runtime. It plays a vital role in enhancing the robustness and resilience of a program, ultimately resulting in a better user experience. Consequently, software developers must possess the necessary skills to manage and handle exceptions effectively. In this article, we have explored the most frequently asked interview questions related to exception handling, which are relevant for both fresher and experienced developers.

No comments:

Post a Comment