Java Exception Handling Question and Answers

1. What are the exception handling keyword in Java?
  There are four keywords used in java exception handling.
  • throw: Sometimes we explicitly want to create exception object and then throw it to halt the normal processing of the program. throw keyword is used to throw exception to the run time to handle it.
  • throws: when we are throwing any checked exception in a method and not handling it, then we need to use throws keyword in method signature to let caller program know the exceptions that might be thrown by the method. The caller method might handle these exceptions or propagate it to its caller method using throws method. We can provide multiple exceptions in the throws clause and it can be used with main() method also.
  • try-catch: We use try catch block for exception handling in our code. try is the start of the block and catch is at the end of try block to handle the exceptions. We can have multiple catch blocks with a try and try catch block can be nested also. Catch block requires a parameter that should be of Type Exception.
  • finally: finally block is optional and can be used only with try catch block. Since exception halts the process of execution, we might have some resources open that will not get closed, so we can use fin
 
Your Name Your Email-ID
Your Answer
2. What is the use of the finally block?
  Finally is the block of code that is always executed even when an exception has occurred.
 
Your Name Your Email-ID
Your Answer
3. Explain Java Exception Hierarchy?
 
  • Java Exceptions are hierarchical and inheritance is used to categorize different types of exceptions. Throwable is the parent class of Java Exceptions Hierarchy and it has two child objects – Error and Exception. Exceptions are further divided into checked exceptions and run time exceptions.
  • Errors are exceptional scenarios that are out of scope of application and its not possible to anticipate and recover from them, for example hardware failure, JVM crash or out of memory error.
  • Checked Exceptions are exceptional scenarios that we can anticipate in a program and try to recover from it, for example FileNotFoundException. We should catch this exception and provide useful message to user and log it properly for debugging purpose. Exceptions is the parent class of all Checked Exceptions.
  • Runtime Exceptions are caused by bad programming, for example trying to retrieve an element from the Array. We should check the length of array first before trying to retrieve the element otherwise it might throw ArrayIndexOutofBoundException at runtime. Runtime Exception is the parent class of all runtime exceptions.
 
Your Name Your Email-ID
Your Answer
4. What classes of exceptions may be throw statement?
  A throw statement may throw any expression that may be assigned to the Throwable type.
 
Your Name Your Email-ID
Your Answer
1234 Page 1 of 4