Java Exception Handling Interview Questions and Answers
Ques 26. What is the 'NullPointerException' and how can you prevent it?
'NullPointerException' occurs when you try to access or modify an object reference that is null. You can prevent it by checking for null before accessing the object.
Example:
if (obj != null) { /* code using obj */ }
Ques 27. Explain the 'try', 'catch', 'finally' and 'throw' keywords in Java.
'try' is used to enclose a block of code where exceptions might occur. 'catch' is used to handle exceptions. 'finally' is used to define a block of code that will be executed whether an exception is thrown or not. 'throw' is used to explicitly throw an exception.
Ques 28. What is the purpose of the 'Assertion' in Java?
Assertions are used to test assumptions about the program. They help in identifying logical errors during development and testing.
Example:
assert x > 0 : "x should be greater than 0";
Ques 29. How can you handle exceptions in a servlet?
In servlets, exceptions can be handled using the 'try-catch' block or by declaring them in the 'throws' clause of the method.
Ques 30. 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: