Java Exception Handling Interview Questions and Answers
Freshers / Beginner level questions & answers
Ques 1. What is an exception in Java?
An exception is an event that disrupts the normal flow of the program's instructions during runtime.
Example:
int result = 10 / 0; // This will throw an ArithmeticException
Ques 2. What is the purpose of the 'finally' block in exception handling?
The 'finally' block is used to execute important code such as closing resources, whether an exception is thrown or not.
Ques 3. What is the purpose of the 'throw' keyword?
The 'throw' keyword is used to explicitly throw an exception.
Example:
throw new CustomException("This is a custom exception");
Ques 4. Can you have a try block without a catch block?
Yes, you can have a try block without a catch block if there is a finally block.
Example:
try { /* code */ } finally { /* cleanup code */ }
Ques 5. What is the purpose of the 'NullPointerException' in Java?
The 'NullPointerException' is thrown when attempting to access or modify an object reference that is null.
Example:
String str = null;
int length = str.length(); // This will throw NullPointerException
Ques 6. What is the purpose of the 'try' block?
The 'try' block is used to enclose a block of code where exceptions might occur.
Example:
try { /* code that may throw exceptions */ } catch (Exception e) { /* handle exception */ }
Ques 7. What is the purpose of the 'RuntimeException' class?
'RuntimeException' is the superclass of those exceptions that can be thrown during the normal operation of the Java Virtual Machine.
Ques 8. What is the purpose of the 'AssertionError' class?
'AssertionError' is thrown to indicate that an assertion has failed. It extends 'Error' class.
Ques 9. What is the purpose of the 'Error' class in Java?
'Error' class represents serious errors that are not meant to be caught or handled by applications.
Ques 10. How do you handle custom exceptions in a try-catch block?
You can catch custom exceptions like any other exception by specifying the custom exception type in the catch block.
Example:
try { /* code */ } catch (CustomException ce) { /* handle custom exception */ }
Ques 11. What is the purpose of the 'FileNotFoundException' in Java?
'FileNotFoundException' is thrown when an attempt to open the file denoted by a specified pathname has failed.
Example:
try { FileReader fr = new FileReader("nonexistent.txt"); }
catch (FileNotFoundException e) { /* handle file not found exception */ }
Most helpful rated by users: