Saturday 28 April 2012

JAVA interview questions 25

Q241. What is the purpose of throw? 
Ans. Sometimes we can create Exception object explicitly and we can handover that exception object to the JVM explicitly by throw keyword. 
The purpose of throw keyword is to handover our created exception object explicitly to the
JVM.
Example1: 
class Test{ 
public static void main(String[] args){ 
System.out.println(10/0); 


In this case ArithmeticException object created implicitly and handover to the JVM automatically by the main method. 
Example2: 
class Test{ 
Public static void main(String[] args){ 
Throw new ArithmeticException(“/by Zero”); } 

In this case creation of an exception object and handover to the JVM explicitly by the programmer. 

Q242. Is it possible to throw an Error? 
Ans. Yes, It is possible to throw any Throwable type including Error. 

Q243. Is it possible to throw any java object? 
Ans. No, we can use throw keyword only for throwable objects otherwise we will get compile time error saying incompatible type. 
* Core Java 
* Servlets & JSP 
* Struts 
* EJB 
* J2ME 

Q244. After throw is it allow to take any statement directly? 
Ans. After throw statement we are not allow to place any statement directly violation leads to compile time error saying Unreachable Statement. 

Q245. What is the purpose of throws? 
Ans. The main purpose of throws keyword is to delegate the responsibilities of exception handling to the caller. It requires in the case of checked exception. 

Q246. What is the difference between throw and throws? 
Ans. Sometimes we can create Exception object explicitly and we can handover that exception object to the JVM explicitly by throw keyword.The main purpose of throw keyword is to 
handover our created exception object explicitly to the JVM. The main purpose of throws 
keyword is to delegate the responsibilities of exception handling to the caller. It requires in the case of checked exception. 

Q47. What is the difference between throw and thrown? 
Ans. There is no terminology of thrown in java. 

Q248. Is it possible to use throws keyword for any java class? 
Ans. No, we can use throws keyword only for Throwable classes. Otherwise we will get compile time error saying Incompatible types. 

Q249. If we are taking catch block for an exception but there is no chance of rising that exception in try then what will happen? 
Ans. If there is no chance of raising an exception in try then we are not allow to write catch 
block for that exception violation leads to compile time error. But this rule is applicable only for fully checked exception. 

Q250. Explain Exception Handling keyword? 
Ans. Exception Handling keyword: Try :- To maintain Risky code. 
Catch:- To maintain Exception Handling code. Finally:- To maintain the clean up code. 
Throw:- To handover our created exception object to the JVM explicitly. 
Throws:- To delegate the responsibilities of Exception Handling to the caller. 

No comments:

Post a Comment