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" 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");
}
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?
- try, catch, finally ===> Valid.
- try, catch, catch ===> Valid (multiple catch blocks valid).
- try, finally ===> Valid (without catch block it will be abnormal termination, but through finally we can close resources. so it is Valid).
- only try block ===> Not Valid (catch or finally block is required with try block).
- only catch block ===> Not Valid (try block is required with catch block).
- 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?
- Yes, finally block will be always executed as it is mainly used to closed the open resources.
- 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)
11.How to create custom exception in Java?
- Create a new class whose should end with an Exception.
- Make the class extends Exception.
- Create a constructor with a String parameter.
- 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);
}
}
- The first constructor takes no arguments and simply calls the superclass constructor.
- The second constructor takes a message argument and passes it to the superclass constructor.
- The third constructor takes a Throwable cause argument and passes it to the superclass constructor.
- 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.
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.
Output:
Caught exception: This is a custom exception
MyException: This is a custom exception
at Example.main(Example.java:5)
No comments:
Post a Comment