Sponsored Links
Ad by Google
Recently, I have completed BlockingQueue Tutorial and Exception Tutorial, after completion of Exception tutorial now planning to start specific exception handling interview questions. Although, I have already posted 15 core java written interview question and 20 core java basic interview questions, but in this post, I shall post top 20 only exception related interview questions like specific 20 jsp-servlet interview questions.
Well Exception is very popular topic in any java , j2ee interview and definitely you will faced at least 2 questions on this topic. I am going to list top 20 frequently asked questions on exception and mostly started with the words like "Have you used exception in your code"?
1. What is difference between Checked Exception and Unchecked Exception?
This question is almost every interviewer asked, and it seems it is very common interview question like why string is immutable?
Well, both Checked and Unchecked Exceptions are derived from java.lang.Throwable,that means Throwable is base class for both checked and unchecked exception, but Checked exceptions are those exception which are forced by java compiler to catch it or throws it at compile time otherwise code will not compile successfully, whereas Unchecked exceptions are bugs,logical error in your code and it can be identified only at Runtime.
In java all Exceptions are checked exception, except java.lang.Error or it's sub classes and java.lang.Runtime or it's sub classes.
The NullPointerException,ArithmeticException,ClassCastException etc. are example of Unchecked Exceptions and IOException,FileNotFoundException,InterruptedException etc. are example of Checked Exception. This is very huge topic, So I have separately listed the complete differences in my another post, You can read more about all the differences between checked and unchecked exception
2. What is difference between throw and throws keyword in java?
This is again a common java interview question and popular like What is difference between Externalizable and Serializable
Well, both keywords are used in Exception handling, throws keyword is used with method signature to declare that this method is going to throw one or more declared Exceptions like throws IOException,InterruptedException whereas throw keyword used within a method/static block and throw only one Exception at a time.
The throws keyword followed with Class name like throws IOException whereas throw keyword is followed with an instance like throw new FileNotFoundException()
Code example of throw keyword -
3. How to create custom exception in java?
Yes, this question is still popular, like still on demand what are the new features of JDK 7
Interviewer just want check your working knowledge over Exception, you can simply reply with that you can create custom exception either by extending java.lang.Exception class or java.lang.Runtime
Example,
Than you have to say one is checked custom exception and another one is unchecked custom exception, so checked exception will forced you to handled it at compile time whereas unchecked exception will occurred at Runtime, so no need to handled it. Here is a complete example of Custom Exception in java with explanation.
4. What is difference between extending Exception and extending RuntimeException?
Interviewer sometimes ask you this question instead of What is difference between Checked and Unchecked Exception, to make you confused. This question is also popular as HashMap vs Hashtable
To answer correctly of this question, you need to understand what is exception and how many types of exception, so I suggest you to read about exception from Exception Tutorial.
In short, extending Exception will create Checked exception and we know that checked exceptions are forced by compiler to handle it or throws it at compile time otherwise program will not compile successfully, Whereas extending java.lang.RuntimeException will create unchecked exception and unchecked exceptions are occurs at runtime, so no need to handle it, because program will not recover from such exceptions. For detail example you can follow the previous tutorial How to create custom exception with example
5. Which one is the parent of all the Exceptions except java.lang.Object
Short question, so answer is also short java.lang.Throwable is a parent of all the Exceptions, you can see an Exception hierarchy image for more details.
6. List the Exception Handling keywords
This question's popularity is equal to list the methods of java.lang.Object class. Well five exception handling keywords and those are listed below -
One of my favorite exception handling interview questions like ArrayList vs LinkedList, Errors and Exceptions both are sub-classes of java.lang.Throwable.
Errors - An errors are also known as Unchecked exceptions and it occurs at runtime. Errors are indication of serious problems, and from errors your application cannot be recovered, so never try to handle it or throws it.
One example of Error is,
VirtualMachineError- Thrown of this error indicates that, virtual machine is crashed/broken or resource is not available for java virtual machine, and it'll caused any of these errors -
Checked Exception examples, FileNotFoundException,DataFormatException,TimeoutException etc.
8. What is try with resources
The try with resources is a statement, which declares one or more close able resources. That closeable resources must be automatically closed after the program finished with this execution.
Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a closeable resource.
Below is the syntax of try-with-resources statement.
9. Does finally block always executed?
Big Yes, finally block will always executed unless and until application killed in try or catch block.
10. What will be the output of this program?
11. Is it possible to use multiple catch block with single try block?
Say Big yes, below is the syntax -
12. Can you draw a Exception Hierarchy?
You can took help from our previous answer of question no 5 or Exception Tutorial.
13. Can you list down few Unchecked Exception
The Unchecked exception are those exceptions, which occurs at runtime and your application cannot recovered from the Unchecked exceptions, Unchecked exceptions includes both java.lang.RuntimeException as well as java.lang.Error below are the few examples of Unchecked exceptions -
14. What is difference between ClassNotFoundException and NoClassDefFoundError?
This is one of the popular java interview question, like balancing parenthesis, Well both are the sub-class of java.lang.Throwable.
The ClassNotFoundException is a checked exception and thrown when an application tries to load a class through it's string name using any of these methods and class definition not found.
15. How to handled exception in java?
To handle an exception, java provide three different exception handling keywords and those are - try,catch, and finally with the help of these keywords you can write an exception handler. You can find the complete details about the exception handling keywords at here.
16. What will be the output of below program?
Although StackOverFlowException is a sub-class of java.lang.Error, but you can create code to generate this exception you can use recursive method with never ending process which will generate this exception, below is the syntax to generate StackOverFlowException -
18. Can you list down few Checked Exceptions
Below are the few examples of Checked Exceptions -
19. What is ArrayIndexOutOfBoundsException and how to prevent this error.
This is a sub-class of java.lang.RuntimeException exception and thrown to indicate, that the array has been accessed with illegal index, might be with any negative value or greater than or equal to the size of an array.
For example if array is initialized with int[]myArray = new int[4], and accessing through myArray[4] will throws an ArrayIndexOutOfBoundExcepiont, because array index is started with 0, so the last element from the above array can be accessed with myArray[3].
20. Can we throw Object instead of any exception
No you cannot throw Object instead of any exception, You can throw any instance of java.lang.Throwable
That's it, these 20 questions and Exception Tutorial will helps you to give the correct answer of any exception related interview questions.
Well Exception is very popular topic in any java , j2ee interview and definitely you will faced at least 2 questions on this topic. I am going to list top 20 frequently asked questions on exception and mostly started with the words like "Have you used exception in your code"?
1. What is difference between Checked Exception and Unchecked Exception?
This question is almost every interviewer asked, and it seems it is very common interview question like why string is immutable?
Well, both Checked and Unchecked Exceptions are derived from java.lang.Throwable,that means Throwable is base class for both checked and unchecked exception, but Checked exceptions are those exception which are forced by java compiler to catch it or throws it at compile time otherwise code will not compile successfully, whereas Unchecked exceptions are bugs,logical error in your code and it can be identified only at Runtime.
In java all Exceptions are checked exception, except java.lang.Error or it's sub classes and java.lang.Runtime or it's sub classes.
The NullPointerException,ArithmeticException,ClassCastException etc. are example of Unchecked Exceptions and IOException,FileNotFoundException,InterruptedException etc. are example of Checked Exception. This is very huge topic, So I have separately listed the complete differences in my another post, You can read more about all the differences between checked and unchecked exception
2. What is difference between throw and throws keyword in java?
This is again a common java interview question and popular like What is difference between Externalizable and Serializable
Well, both keywords are used in Exception handling, throws keyword is used with method signature to declare that this method is going to throw one or more declared Exceptions like throws IOException,InterruptedException whereas throw keyword used within a method/static block and throw only one Exception at a time.
The throws keyword followed with Class name like throws IOException whereas throw keyword is followed with an instance like throw new FileNotFoundException()
Code example of throw keyword -
public static int getNum(String str) { throw new IllegalArgumentException("Not a valid number"); }Code example of throws keyword -
public static int getNum(String str) throws NumberFormatException { return Integer.parseInt(str); }
3. How to create custom exception in java?
Yes, this question is still popular, like still on demand what are the new features of JDK 7
Interviewer just want check your working knowledge over Exception, you can simply reply with that you can create custom exception either by extending java.lang.Exception class or java.lang.Runtime
Example,
public class MyException extends Exception { } public class MyRuntimeException extends RuntimeException { }After that, interviewer asked you, what is the difference between these two different way of creating custom exception.
Than you have to say one is checked custom exception and another one is unchecked custom exception, so checked exception will forced you to handled it at compile time whereas unchecked exception will occurred at Runtime, so no need to handled it. Here is a complete example of Custom Exception in java with explanation.
4. What is difference between extending Exception and extending RuntimeException?
Interviewer sometimes ask you this question instead of What is difference between Checked and Unchecked Exception, to make you confused. This question is also popular as HashMap vs Hashtable
To answer correctly of this question, you need to understand what is exception and how many types of exception, so I suggest you to read about exception from Exception Tutorial.
In short, extending Exception will create Checked exception and we know that checked exceptions are forced by compiler to handle it or throws it at compile time otherwise program will not compile successfully, Whereas extending java.lang.RuntimeException will create unchecked exception and unchecked exceptions are occurs at runtime, so no need to handle it, because program will not recover from such exceptions. For detail example you can follow the previous tutorial How to create custom exception with example
5. Which one is the parent of all the Exceptions except java.lang.Object
Short question, so answer is also short java.lang.Throwable is a parent of all the Exceptions, you can see an Exception hierarchy image for more details.
6. List the Exception Handling keywords
This question's popularity is equal to list the methods of java.lang.Object class. Well five exception handling keywords and those are listed below -
- try-catch
- finally
- try-with-resources
- throws
- throw
One of my favorite exception handling interview questions like ArrayList vs LinkedList, Errors and Exceptions both are sub-classes of java.lang.Throwable.
Errors - An errors are also known as Unchecked exceptions and it occurs at runtime. Errors are indication of serious problems, and from errors your application cannot be recovered, so never try to handle it or throws it.
One example of Error is,
VirtualMachineError- Thrown of this error indicates that, virtual machine is crashed/broken or resource is not available for java virtual machine, and it'll caused any of these errors -
- InternalError
- OutOfMemoryError
- StackOverflowError
- UnknownError
Checked Exception examples, FileNotFoundException,DataFormatException,TimeoutException etc.
8. What is try with resources
The try with resources is a statement, which declares one or more close able resources. That closeable resources must be automatically closed after the program finished with this execution.
Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a closeable resource.
Below is the syntax of try-with-resources statement.
public void tryWithResources() throws IOException { try (BufferedReader br = new BufferedReader(new FileReader("test.txt"))) { System.out.println(br.readLine()); } }Now, BufferdReader will automatically closed after completion of tryWithResources method, this feature was introduced in JDK-7 you can read more about jdk 7 new features.
9. Does finally block always executed?
Big Yes, finally block will always executed unless and until application killed in try or catch block.
10. What will be the output of this program?
public boolean errorCheck() { boolean b; try { b = true; throw new ArithmeticException("arithmetic exception"); } catch (Exception e) { b = false; } finally { b = true; } return b; }
11. Is it possible to use multiple catch block with single try block?
Say Big yes, below is the syntax -
try { FileReader fr = new FileReader(file); fr.read(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd"); sdf.parse("2015-09-09"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (ParseException pe) { pe.printStackTrace(); } catch (IOException pe) { pe.printStackTrace(); }
12. Can you draw a Exception Hierarchy?
You can took help from our previous answer of question no 5 or Exception Tutorial.
13. Can you list down few Unchecked Exception
The Unchecked exception are those exceptions, which occurs at runtime and your application cannot recovered from the Unchecked exceptions, Unchecked exceptions includes both java.lang.RuntimeException as well as java.lang.Error below are the few examples of Unchecked exceptions -
- ArithmeticException
- ClassCastException
- NullPointerException
- ConcurrentModificationException
- StackOverflowError
- OutOfMemoryError
14. What is difference between ClassNotFoundException and NoClassDefFoundError?
This is one of the popular java interview question, like balancing parenthesis, Well both are the sub-class of java.lang.Throwable.
The ClassNotFoundException is a checked exception and thrown when an application tries to load a class through it's string name using any of these methods and class definition not found.
- forName
- findSystemClass
- loadClass
15. How to handled exception in java?
To handle an exception, java provide three different exception handling keywords and those are - try,catch, and finally with the help of these keywords you can write an exception handler. You can find the complete details about the exception handling keywords at here.
16. What will be the output of below program?
package com.javamakeuse.poc; public class ExceptionIQ { public static void main(String[] args) { try { m1(); System.out.println("try"); } catch (Exception e) { System.out.println("catch"); } finally { System.out.println("finally"); } } public static void m1() { throw new Error("error"); } }17. Can you write a program to generate StackOverFlowException
Although StackOverFlowException is a sub-class of java.lang.Error, but you can create code to generate this exception you can use recursive method with never ending process which will generate this exception, below is the syntax to generate StackOverFlowException -
List list1 = new ArrayList<>(); List list2 = new ArrayList<>(); list1.add(list2); list2.add(list1); System.out.println(list1.equals(list2));
18. Can you list down few Checked Exceptions
Below are the few examples of Checked Exceptions -
- IOException
- FileNotFoundException
- SQLException
- TimeoutException
- InterruptedException
19. What is ArrayIndexOutOfBoundsException and how to prevent this error.
This is a sub-class of java.lang.RuntimeException exception and thrown to indicate, that the array has been accessed with illegal index, might be with any negative value or greater than or equal to the size of an array.
For example if array is initialized with int[]myArray = new int[4], and accessing through myArray[4] will throws an ArrayIndexOutOfBoundExcepiont, because array index is started with 0, so the last element from the above array can be accessed with myArray[3].
20. Can we throw Object instead of any exception
No you cannot throw Object instead of any exception, You can throw any instance of java.lang.Throwable
That's it, these 20 questions and Exception Tutorial will helps you to give the correct answer of any exception related interview questions.
Sponsored Links
Nice article hoping to read more of these from you.
ReplyDeletestruts training in chennai|struts training|struts training center in chennai|struts course in chennai