exception handling in java faqs

Upload: mahadeva-pariwar

Post on 07-Jul-2018

232 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/18/2019 Exception Handling in Java FAQS

    1/44

    1

    EXCEPTIONS - Top 60 interview questions and answers in java for fresher andexperienced - 30 important OUTPUT questions Set-2 > Q26- Q60 

    Question 1. What is exception in java? Answer . Java Exception handling provides a mechanism to handle compile andruntime errors.

      To make application robust Exception must be handled appropriately,  by handling exceptions we end up giving some meaningful message to end user

    rather than giving meaningless message.

    Question 2. Explain exception hierarchy in java? Answer . Exception hierarchy > 

     java.lang.Object is superclass of all classes in java. 

     java.lang.Throwable is superclass of java.lang.Exception and java.lang.Error  

     java.lang.Exception is superclass of java.lang.RuntimeException, IOException,

    SQLException, BrokenBarrierException and many more other classes in java. 

     java.lang.RuntimeException is superclass of java.lang.NullPointerException, ArithmeticException and many more other classes in java. 

     java.lang.Error  is superclass of java.lang.VirtualMachineError, IOError, AssertionError,ThreadDeath and many more other classes in java. 

     java.lang.VirtualMachineError is superclass of java.lang.OutOfMemoryError,StackOverflowError and many more other classes in java. 

    http://www.javamadesoeasy.com/2015/05/exceptions-top-60-interview-questions_75.htmlhttp://www.javamadesoeasy.com/2015/05/exceptions-top-60-interview-questions_75.htmlhttp://www.javamadesoeasy.com/2015/05/exceptions-top-60-interview-questions_75.htmlhttp://www.javamadesoeasy.com/2015/03/cyclicbarrier-in-java.htmlhttp://www.javamadesoeasy.com/2015/03/cyclicbarrier-in-java.htmlhttp://www.javamadesoeasy.com/2015/03/cyclicbarrier-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.htmlhttp://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.htmlhttp://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.htmlhttp://www.javamadesoeasy.com/2015/05/nullpointerexception-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/nullpointerexception-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/nullpointerexception-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/javalangerror-in-exception-handling-in.htmlhttp://www.javamadesoeasy.com/2015/05/javalangerror-in-exception-handling-in.htmlhttp://www.javamadesoeasy.com/2015/05/javalangerror-in-exception-handling-in.htmlhttp://www.javamadesoeasy.com/2015/04/threaddeath-error-calling-stop-method.htmlhttp://www.javamadesoeasy.com/2015/04/threaddeath-error-calling-stop-method.htmlhttp://www.javamadesoeasy.com/2015/04/threaddeath-error-calling-stop-method.htmlhttp://www.javamadesoeasy.com/2015/05/javalangerror-in-exception-handling-in.htmlhttp://www.javamadesoeasy.com/2015/05/nullpointerexception-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.htmlhttp://www.javamadesoeasy.com/2015/03/cyclicbarrier-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/exceptions-top-60-interview-questions_75.htmlhttp://www.javamadesoeasy.com/2015/05/exceptions-top-60-interview-questions_75.html

  • 8/18/2019 Exception Handling in Java FAQS

    2/44

    2

    Question 3. What are differences between checkedand unchecked exceptions? Answer . 

    Property 

    checked except ion  

    unchecked except ion  

    1   Also known as  checked exceptions arealso known ascompileTime exceptions. 

    unchecked exceptions are alsoknown as runtime exceptions. 

    2  Should be solvedat compile orruntime? 

    Checked exceptions arethose which need to betaken care at compile time. 

    Unchecked exceptions are thosewhich need to be taken care atruntime. 

    3  Benefit/ Advantage 

    We cannot proceed untilwe fix compilation issues

    which are most likely tohappen in program, thishelps us in avoidingruntime problems upto lotof extent. 

    Whenever runtime exception occursexecution of program is interrupted,

    but by handling these kind ofexception we avoid such interruptionsand end up giving some meaningfulmessage to user. 

    4  Creatingcustom/ownexception 

    class UserException extends Exception { 

    UserException(String s) { super(s); 

    } } 

    By extending

     java.lang.Exception, wecan create checkedexception. 

    class UserException extends RuntimeException { 

    UserException(String s) { super(s); 

    } } 

    By extending

     java.lang.RuntimeException, wecan create unchecked exception. 

    5  Exceptionpropagation

    For propagating checkedexceptions method mustthrow exception by usingthrows keyword. 

    unchecked exceptions areautomatically propagated in java. 

    6  handling checked

    and uncheckedexception whileoverridingsuperclassmethod 

    If superclass method

    throws/declare checked  except ion > 

      overridden methodof subclass candeclare/throw narrower (subclassof) checkedexception (Asshown in Program),or

      overridden methodof subclass cannot

    If superclass method

    throws/declare unchecked  > 

      overridden method ofsubclass can declare/throwany unchecked /RuntimeException(superclass or subclass) (Asshown in Program), or  

      overridden method ofsubclass cannotdeclare/throw any checkedexception (As shown in

    http://www.javamadesoeasy.com/2015/05/exception-propagation-in-java-deep.htmlhttp://www.javamadesoeasy.com/2015/05/exception-propagation-in-java-deep.htmlhttp://www.javamadesoeasy.com/2015/05/exception-propagation-in-java-deep.htmlhttp://www.javamadesoeasy.com/2015/05/exception-propagation-in-java-deep.htmlhttp://www.javamadesoeasy.com/2015/05/program-to-show-overridden-method-of_93.htmlhttp://www.javamadesoeasy.com/2015/05/program-to-show-overridden-method-of_93.htmlhttp://www.javamadesoeasy.com/2015/05/program-to-show-overridden-method-of_93.htmlhttp://www.javamadesoeasy.com/2015/05/program-to-show-overridden-method-of.htmlhttp://www.javamadesoeasy.com/2015/05/program-to-show-overridden-method-of.htmlhttp://www.javamadesoeasy.com/2015/05/program-to-show-overridden-method-of.htmlhttp://www.javamadesoeasy.com/2015/05/program-to-show-overridden-method-of.htmlhttp://www.javamadesoeasy.com/2015/05/program-to-show-overridden-method-of_93.htmlhttp://www.javamadesoeasy.com/2015/05/exception-propagation-in-java-deep.htmlhttp://www.javamadesoeasy.com/2015/05/exception-propagation-in-java-deep.htmlhttp://www.javamadesoeasy.com/2015/05/exception-propagation-in-java-deep.html

  • 8/18/2019 Exception Handling in Java FAQS

    3/44

    3

    declare/throw broader(superclass of)checked exception(As shown in

    Program), or  overridden method

    of subclass candeclare/throw anyunchecked /RuntimeException (As shown inProgram) 

    Program),

    Which classes arewhich type of

    exception? eitherchecked or  unchecked exception?

     

    The class Exception andall its subclasses that are

    not also subclasses ofRuntimeException arechecked exceptions. 

    The class RuntimeException and allits subclasses are unchecked

    exceptions. 

    Likewise, The class Error and all itssubclasses are uncheckedexceptions. 

    7  Most frequentlyfaced exceptions 

    SQLException, IOException,ClassNotFoundException  

    NullPointerException,  ArithmeticException ArrayIndexOutOfBoundsException. 

    Read more on : Checked (compile time exceptions) and UnChecked(RuntimeExceptions) in java - Definition and differences

     

    Question 4. What are 5 exception handling keywordsin java?Answer . 5  keyword  in java except ion hand ling  

     

    try - Any exception occurring in try block is catched by catch block.

     

      catch - catch block is always followed by try block. 

      finally f inal ly b lock can can only exist if try or try-catch block isthere, finally block can’t be used alone in java. 

    Features of finally > 

    http://www.javamadesoeasy.com/2015/05/program-to-show-overridden-method-of_94.htmlhttp://www.javamadesoeasy.com/2015/05/program-to-show-overridden-method-of_94.htmlhttp://www.javamadesoeasy.com/2015/05/program-to-show-overridden-method-of_37.htmlhttp://www.javamadesoeasy.com/2015/05/program-to-show-overridden-method-of_37.htmlhttp://www.javamadesoeasy.com/2015/05/program-to-show-overridden-method-of_6.htmlhttp://www.javamadesoeasy.com/2015/05/program-to-show-overridden-method-of_6.htmlhttp://www.javamadesoeasy.com/2015/05/sqlexception-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/sqlexception-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/nullpointerexception-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/nullpointerexception-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.htmlhttp://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.htmlhttp://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.htmlhttp://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.htmlhttp://www.javamadesoeasy.com/2015/05/keywords-in-java-language.htmlhttp://www.javamadesoeasy.com/2015/05/keywords-in-java-language.htmlhttp://www.javamadesoeasy.com/2015/05/keywords-in-java-language.htmlhttp://www.javamadesoeasy.com/2015/05/try-catch-finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/try-catch-finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/try-catch-finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/try-catch-finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/try-catch-finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/try-catch-finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/try-catch-finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/try-catch-finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/try-catch-finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/keywords-in-java-language.htmlhttp://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.htmlhttp://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.htmlhttp://www.javamadesoeasy.com/2015/05/nullpointerexception-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/sqlexception-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/program-to-show-overridden-method-of_6.htmlhttp://www.javamadesoeasy.com/2015/05/program-to-show-overridden-method-of_37.htmlhttp://www.javamadesoeasy.com/2015/05/program-to-show-overridden-method-of_94.html

  • 8/18/2019 Exception Handling in Java FAQS

    4/44

    4

      finally block is always executed irrespective of exception is thrown ornot.

      finally is keyword in java.  finally block is optional in java, we may use it or not.

    finally block is not executed  in following scenarios > 

      finally is not executed when System.exit is called.  if in case JVM crashes because of some java.util.Error . 

      throw throw is a keyword in java.  throw keyword allows us to throw checked or unchecked exception. 

      throws throws is written in method’s definition to indicate that methodcan throw exception. 

    Question 5. Explain what is Error in java? 

    Answer . jav a.lang .Error    Error is a subclass of Throwable  Error indicates some serious problems that our application should not try to

    catch.   Errors are abnormal conditions in application.  Error and its subclasses are regarded as unchecked exceptions

    Must know : ThreadDeath is an error which application must not try to catch but it is normal condition.  

    Question 6. What are differences between Exceptionand Error in java? Answer .

    Property  Exception   Error  

    1  seriousproblem? 

    Exception does not indicateany serious problem. 

    Error indicates some seriousproblems that our applicationshould not try to catch. 

    http://www.javamadesoeasy.com/2015/05/javalangerror-in-exception-handling-in.htmlhttp://www.javamadesoeasy.com/2015/05/javalangerror-in-exception-handling-in.htmlhttp://www.javamadesoeasy.com/2015/05/javalangerror-in-exception-handling-in.htmlhttp://www.javamadesoeasy.com/2015/05/throw-exception-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/throw-exception-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.htmlhttp://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.htmlhttp://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.htmlhttp://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.htmlhttp://www.javamadesoeasy.com/2015/05/exception-handling-exception-hierarchy.htmlhttp://www.javamadesoeasy.com/2015/05/exception-handling-exception-hierarchy.htmlhttp://www.javamadesoeasy.com/2015/05/exception-handling-exception-hierarchy.htmlhttp://www.javamadesoeasy.com/2015/05/throws-exception-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/throws-exception-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/exception-handling-exception-hierarchy.htmlhttp://www.javamadesoeasy.com/2015/05/exception-handling-exception-hierarchy.htmlhttp://www.javamadesoeasy.com/2015/05/exception-handling-exception-hierarchy.htmlhttp://www.javamadesoeasy.com/2015/05/javalangerror-in-exception-handling-in.htmlhttp://www.javamadesoeasy.com/2015/05/javalangerror-in-exception-handling-in.htmlhttp://www.javamadesoeasy.com/2015/04/threaddeath-error-calling-stop-method.htmlhttp://www.javamadesoeasy.com/2015/04/threaddeath-error-calling-stop-method.htmlhttp://www.javamadesoeasy.com/2015/05/exception-handling-exception-hierarchy.htmlhttp://www.javamadesoeasy.com/2015/05/exception-handling-exception-hierarchy.htmlhttp://www.javamadesoeasy.com/2015/05/javalangerror-in-exception-handling-in.htmlhttp://www.javamadesoeasy.com/2015/05/javalangerror-in-exception-handling-in.htmlhttp://www.javamadesoeasy.com/2015/05/javalangerror-in-exception-handling-in.htmlhttp://www.javamadesoeasy.com/2015/05/exception-handling-exception-hierarchy.htmlhttp://www.javamadesoeasy.com/2015/04/threaddeath-error-calling-stop-method.htmlhttp://www.javamadesoeasy.com/2015/05/javalangerror-in-exception-handling-in.htmlhttp://www.javamadesoeasy.com/2015/05/exception-handling-exception-hierarchy.htmlhttp://www.javamadesoeasy.com/2015/05/throws-exception-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/exception-handling-exception-hierarchy.htmlhttp://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.htmlhttp://www.javamadesoeasy.com/2015/05/throw-exception-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/javalangerror-in-exception-handling-in.html

  • 8/18/2019 Exception Handling in Java FAQS

    5/44

    5

    2  divided intochecked andunchecked 

    Exception are divided intochecked and uncheckedexceptions. 

    Error are not divided further intosuch classifications. 

    3  Which classes

    are whichtype ofexception?eitherchecked or  unchecked exception? 

    The class Exception and all its

    subclasses that are not alsosubclasses ofRuntimeException arechecked exceptions. 

    The class RuntimeExceptionand all its subclasses areunchecked exceptions. Likewise, The class Error and all itssubclasses are uncheckedexceptions. 

    Error and its subclasses are regarded

    as unchecked exceptions

    4  Mostfrequentlyfacedexception anderrors 

    checked exceptions> SQLException,IOException,ClassNotFoundException 

    unchecked exceptions> NullPointerException,  ArithmeticException, 

    VirtualMachineError, IOError,AssertionError, ThreadDeath, OutOfMemoryError,StackOverflowError. 

    5  Why to catchor not to

    catch? 

     Application must catch theException because they does

    not cause any major threat toapplication. 

     Application must not catch the Errorbecause they does cause any major

    threat to application. 

    Example > Let’s say errors likeOutOfMemoryError andStackOverflowError occur and arecaught then JVM might not be able tofree up memory for rest of applicationto execute, so it will be better ifapplication don’t catch these errorsand is allowed to terminate. 

    Question 7. Explain throw keyword in java? Answer .

      throw is a keyword in java.  throw keyword allows us to throw checked or unchecked exception. 

    th row unchecked exception > 

    http://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.htmlhttp://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.htmlhttp://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.htmlhttp://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.htmlhttp://www.javamadesoeasy.com/2015/05/nullpointerexception-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/nullpointerexception-in-java.htmlhttp://www.javamadesoeasy.com/2015/04/threaddeath-error-calling-stop-method.htmlhttp://www.javamadesoeasy.com/2015/04/threaddeath-error-calling-stop-method.htmlhttp://www.javamadesoeasy.com/2015/04/threaddeath-error-calling-stop-method.htmlhttp://www.javamadesoeasy.com/2015/05/throw-exception-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/throw-exception-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.htmlhttp://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.htmlhttp://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.htmlhttp://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.htmlhttp://www.javamadesoeasy.com/2015/05/exception-handling-exception-hierarchy.htmlhttp://www.javamadesoeasy.com/2015/05/exception-handling-exception-hierarchy.htmlhttp://www.javamadesoeasy.com/2015/05/exception-handling-exception-hierarchy.htmlhttp://www.javamadesoeasy.com/2015/05/exception-handling-exception-hierarchy.htmlhttp://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.htmlhttp://www.javamadesoeasy.com/2015/05/throw-exception-in-java.htmlhttp://www.javamadesoeasy.com/2015/04/threaddeath-error-calling-stop-method.htmlhttp://www.javamadesoeasy.com/2015/05/nullpointerexception-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.htmlhttp://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.html

  • 8/18/2019 Exception Handling in Java FAQS

    6/44

  • 8/18/2019 Exception Handling in Java FAQS

    7/44

    7

     Above code throws NullPointerException (unChecked exception) and didn’t handled it fromwhere method m() was called and no compilation error was thrown.  

    throws Checked exception > 

      We need to handle checked exception either by catching it or throwing it further, ifnot handled we will face compilation error.

    Question 9. What is difference between throw andthrows in java?

     

    Answer .

    throw  throws

    throw keyword is used to throw an exception explicitly. 

    throws keyword isused to declare anexception. 

    2  throw is used inside method. 

    Example > static void m(){

     

    throw new FileNotFoundException(); 

    throws is used in method declaration. 

    Example > static void m()throws FileNotFoundException{ 

    http://www.javamadesoeasy.com/2015/05/throw-exception-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/throw-exception-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/throws-exception-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/keywords-in-java-language.htmlhttp://www.javamadesoeasy.com/2015/05/keywords-in-java-language.htmlhttp://www.javamadesoeasy.com/2015/05/keywords-in-java-language.htmlhttp://www.javamadesoeasy.com/2015/05/exception-handling-exception-hierarchy.htmlhttp://www.javamadesoeasy.com/2015/05/exception-handling-exception-hierarchy.htmlhttp://www.javamadesoeasy.com/2015/05/exception-handling-exception-hierarchy.htmlhttp://www.javamadesoeasy.com/2015/05/exception-handling-exception-hierarchy.htmlhttp://www.javamadesoeasy.com/2015/05/keywords-in-java-language.htmlhttp://www.javamadesoeasy.com/2015/05/throws-exception-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/throw-exception-in-java.html

  • 8/18/2019 Exception Handling in Java FAQS

    8/44

    8

    3  throw is always followed by instanceof Exception class. 

    Example > throw new FileNotFoundException() 

    throws is alwaysfollowed by name ofException class. 

    Example > 

    throws FileNotFoundException 

    4  throw can be used to throw only one exception at time. 

    Example > throw new FileNotFoundException() 

    throws can be used tothrow multipleexception at time. 

    Example > 

    throws FileNotFoundException,NullPointerException 

    and many more... 

    5  throw cannot propagate exception to calling method.  throws can propagateexception to callingmethod. 

    Please see theseprograms to understandhow exception ispropagated to calling

    method. Program 1 - Handling

    Exception by throwing itfrom m() method (usingthrows keyword) andhandling it in try-catchblock from where call tomethod m() was made. 

    Program 2 - ThrowingException from m()method and then again

    throwing it from callingmethod [ i.e. mainmethod] 

    Question 10. How to create user defined checkedand unchecked Exception in java? Answer . 

    http://www.javamadesoeasy.com/2015/05/exception-propagation-in-java-deep.htmlhttp://www.javamadesoeasy.com/2015/05/exception-propagation-in-java-deep.htmlhttp://www.javamadesoeasy.com/2015/05/exception-propagation-in-java-deep.htmlhttp://www.javamadesoeasy.com/2015/05/exception-propagation-in-java-deep.htmlhttp://www.javamadesoeasy.com/2015/05/exception-propagation-in-java-deep.htmlhttp://www.javamadesoeasy.com/2015/05/exception-propagation-in-java-deep.htmlhttp://www.javamadesoeasy.com/2015/05/exception-propagation-in-java-deep.htmlhttp://www.javamadesoeasy.com/2015/05/exception-propagation-in-java-deep.htmlhttp://www.javamadesoeasy.com/2015/05/exception-propagation-in-java-deep.htmlhttp://www.javamadesoeasy.com/2015/05/exception-propagation-in-java-deep.htmlhttp://www.javamadesoeasy.com/2015/05/exception-propagation-in-java-deep.htmlhttp://www.javamadesoeasy.com/2015/05/exception-propagation-in-java-deep.html

  • 8/18/2019 Exception Handling in Java FAQS

    9/44

    9

    Creating user defined  checked  exception > 

    class UserDefinedException extends Exception { UserDefinedException(String s) {

     

    super(s); } 

    By extending java.lang.Exception, we can create checked exception. 

    Creating user defined  unchecked  exception > 

    class UserDefinedException extends RuntimeException { UserDefinedException(String s) { 

    super(s); 

    By extending java.lang.RuntimeException, we can create unchecked exception. 

    Question 11. How to use try-catch-finally ? Can weuse try,catch or finally block alone?

     

    Answer . We can enclose exception prone code in > 

      try-catch block, or

      try-finally block, or  try-catch-finally block.

    Using try-catch blocktry{ 

    //Code to be enclosed in try-catch block 

    }catch(Exception e){ } 

    Using try-finally blocktry{ 

    //Code to be enclosed in try-finally block 

    }finally{ 

    }

    We cannot use try block alone, it must be followed by either catch or finally. 

    Using only try block will cause compilation error  

    try{ 

    http://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.htmlhttp://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.htmlhttp://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.htmlhttp://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.htmlhttp://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.htmlhttp://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.htmlhttp://www.javamadesoeasy.com/2015/05/try-catch-finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/try-catch-finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/try-catch-finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/try-catch-finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.htmlhttp://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.html

  • 8/18/2019 Exception Handling in Java FAQS

    10/44

  • 8/18/2019 Exception Handling in Java FAQS

    11/44

    11

    /*OUTPUT Exception handled - ArithmeticException */ 

    In the above above > ArithmeticException has been used in first catch block RuntimeException has been used in second catch block Exception has been used in third catch block 

    Exception is superclass of RuntimeException andRuntimeException is superclass of ArithmeticException. 

    Question 13. What is Automatic resourcemanagement in java 7? Answer .  As we know java allows us to handle multiple exceptions by using multiplecatch blocks. Now, java 7 has done improvements in multiple exception handling byintroducing multi catch syntax which helps in automatic resource management. 

    Features of mu lt i catch syn tax > 

      Has improved way of catching multiple exceptions.   This syntax does not looks clumsy.  Reduces developer efforts of writing multiple catch blocks.   Allows us to catch more than one exception in one catch block.

    Here is the multi catch syntax > 

    try{ 

    //code . . . . .}catch(IOException | SQLException ex){ 

    //code . . . . . 

    }

    We could separate different exceptions using pipe ( | ) 

    Question 14. Explain try-with-resource in java? Answer . Before java 7, we used to write explicit code for closingfile in finally block by using try-finally block like this > 

    /** Copyright (c), AnkitMittal JavaMadeSoEasy.com */ 

    public class TryWithResourseTest { 

    public static void main(String[] args) throws IOException { 

    InputStream inputStream = null; 

    http://www.javamadesoeasy.com/2015/05/multiple-catch-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/multiple-catch-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/multiple-catch-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/multiple-catch-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/catch-block-and-automatic-resource.htmlhttp://www.javamadesoeasy.com/2015/05/catch-block-and-automatic-resource.htmlhttp://www.javamadesoeasy.com/2015/05/catch-block-and-automatic-resource.htmlhttp://www.javamadesoeasy.com/2015/05/exception-handling-exception-hierarchy.htmlhttp://www.javamadesoeasy.com/2015/05/exception-handling-exception-hierarchy.htmlhttp://www.javamadesoeasy.com/2015/05/exception-handling-exception-hierarchy.htmlhttp://www.javamadesoeasy.com/2015/05/finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/try-catch-finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/try-catch-finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/try-catch-finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/try-catch-finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/exception-handling-exception-hierarchy.htmlhttp://www.javamadesoeasy.com/2015/05/catch-block-and-automatic-resource.htmlhttp://www.javamadesoeasy.com/2015/05/multiple-catch-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/multiple-catch-block-in-java.html

  • 8/18/2019 Exception Handling in Java FAQS

    12/44

    12

    try{ inputStream = new FileInputStream("c:/txtFile.txt"); //code...... 

    }finally{ if(inputStream!=null) 

    inputStream.close(); }

     

    } } 

    In java 7, using Try-with-resources > 

      we need not to write explicit code for closing file.

    import java.io.FileInputStream; 

    import java.io.IOException; import java.io.InputStream; 

    /** Copyright (c), AnkitMittal JavaMadeSoEasy.com */ public class TryWithResourseTest { 

    public static void main(String[] args) throws IOException { 

    try (InputStream inputStream = new FileInputStream("c:/txtFile.txt")) { 

    //code... } 

    } } 

    Using multiple resources inside Try-w ith-resources isalso al lowed. 

    Question 15. Now, question comes why we neednot to close file when we are using Try-with-resources? Answer . Because FileInputStream implements java.lang.AutoCloseable interface (AutoCloseable interface’s close method automatically closes resourceswhich are no longer needed.) 

    Which classes can be used inside Try-with-resources?  All the classes which implements AutoCloseable interface can be used inside Try-with-resources. 

    Question 16. Explain finally keyword in java? 

  • 8/18/2019 Exception Handling in Java FAQS

    13/44

    13

    Answer .try or  try-catch block can be followed by finally block > 

      try-finally block, or  

    try{ //Code to be enclosed in try-finally block 

    }finally{ }

      try-catch-finally block. 

    try{ 

    //Code to be enclosed in try-catch-finally block 

    }catch(Exception e){ }finally{

     

    f inally bloc k can can only exist if try or try-catch block is there, finallyblock can’t be used alone in java. 

    Features of finally > 

      finally block is always executed irrespective of exception is thrown or not.

      finally is keyword in java.

    finally block is not executed  in following scenarios > 

      finally is not executed when System.exit is called.  if in case JVM crashes because of some java.util.Error . 

     Application of finally block in java programs > 

      We may use finally block to execute code for database connection closing,because closing connection in try or catch block may not be safe.

      Why closing connection in try block may not be safe?  Because exception may be thrown in try block before reaching connection

    closing statement.

      Why closing connection in catch block may not be safe?

      Because inappropriate exception may be thrown in try block and we might notenter catch block to close connection.

    http://www.javamadesoeasy.com/2015/05/try-catch-finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/try-catch-finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/try-catch-finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/keywords-in-java-language.htmlhttp://www.javamadesoeasy.com/2015/05/keywords-in-java-language.htmlhttp://www.javamadesoeasy.com/2015/05/keywords-in-java-language.htmlhttp://www.javamadesoeasy.com/2015/05/javalangerror-in-exception-handling-in.htmlhttp://www.javamadesoeasy.com/2015/05/javalangerror-in-exception-handling-in.htmlhttp://www.javamadesoeasy.com/2015/05/javalangerror-in-exception-handling-in.htmlhttp://www.javamadesoeasy.com/2015/05/javalangerror-in-exception-handling-in.htmlhttp://www.javamadesoeasy.com/2015/05/keywords-in-java-language.htmlhttp://www.javamadesoeasy.com/2015/05/try-catch-finally-block-in-java.html

  • 8/18/2019 Exception Handling in Java FAQS

    14/44

    14

    For programs to demonstrate finally. Please refer this post. 

    Question 17. Is it allowed to use nested try-catch in java? Answer . Java exception handling allows us to use nested try-catch block. 

    Nested try-catch block means using try-catch block inside another try-catch block. 

    /** Copyright (c), AnkitMittal JavaMadeSoEasy.com */ public class ExceptionTest {

     

    public static void main(String[] args) { 

    try{  int i=10/0; //will throw ArithmeticException 

    }catch(ArithmeticException ae){ System.out.println("try-catch block handled -

    ArithmeticException"); 

    //using nested try-catch block try{ 

    String s=null; s.charAt(0); //will throw NullPointerException 

    }catch(NullPointerException npe){ 

    System.out.println("NESTED try-catch block handled - " 

    +"NullPointerException"); 

    } } 

    Question 18. Discuss which checked and uncheckedexception can be thrown/declared by subclassmethod while overriding superclass method in java? Answer . 

    If superclass method throws/declare unchecked/Runt imeExcept ion  > 

      overridden method of subclass can declare/throw any unchecked /RuntimeException (superclass or subclass), or  

      overridden method of subclass cannot declare/throw any checked exception, or    overridden method of subclass can declare/throw same exception, or    overridden method of subclass may not declare/throw any exception. 

    http://www.javamadesoeasy.com/2015/05/finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/nested-try-catch-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/nested-try-catch-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/nested-try-catch-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/try-catch-finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/try-catch-finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/try-catch-finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/try-catch-finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/nested-try-catch-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/finally-block-in-java.html

  • 8/18/2019 Exception Handling in Java FAQS

    15/44

  • 8/18/2019 Exception Handling in Java FAQS

    16/44

    16

    return "finally";} 

    } } /*OUTPUT method return -> finally

     

    */ 

    In above program, i=10/0 will throw ArithmeticException and enter catch block to return"catch", but ultimately control will enter finally block to return "finally". 

    Likewise, when try and finally block both return value, method willultimately return value returned by finally block irrespective of valuereturned by try block. For program please refer . 

    Question 20. What is exception propagation in java? Answer . Whenever methods are called stack is formed and an exception is firstthrown from the top of the stack and if it is not caught, it starts coming down the stack toprevious methods until it is not caught.

    If exception remains uncaught even after reaching bottom of the stack it is propagated toJVM and program is terminated.

    Propagating  unchecked  exception(NullPointerException) >

     

    unchecked exceptions are automatically propagated in java. 

    http://www.javamadesoeasy.com/2015/05/try-catch-finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/try-catch-finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/try-catch-finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/what-will-happen-when-catch-and-finally.htmlhttp://www.javamadesoeasy.com/2015/05/what-will-happen-when-catch-and-finally.htmlhttp://www.javamadesoeasy.com/2015/05/what-will-happen-when-catch-and-finally.htmlhttp://javamadesoeasy.com/2015/01/stacks.htmlhttp://javamadesoeasy.com/2015/01/stacks.htmlhttp://javamadesoeasy.com/2015/01/stacks.htmlhttp://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.htmlhttp://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.htmlhttp://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.htmlhttp://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.htmlhttp://javamadesoeasy.com/2015/01/stacks.htmlhttp://www.javamadesoeasy.com/2015/05/what-will-happen-when-catch-and-finally.htmlhttp://www.javamadesoeasy.com/2015/05/try-catch-finally-block-in-java.html

  • 8/18/2019 Exception Handling in Java FAQS

    17/44

    17

    stack  of methods is formed > 

    In the above program, stack is formed and an exception is first thrown from the top of thestack [ method3() ] and it remains uncaught there, and starts coming down the stack toprevious methods to method2(), then to method1(), than to main() and it remains uncaught

    throughout. 

    http://javamadesoeasy.com/2015/01/stacks.htmlhttp://javamadesoeasy.com/2015/01/stacks.htmlhttp://www.javamadesoeasy.com/2015/05/exception-propagation-in-java-deep.htmlhttp://javamadesoeasy.com/2015/01/stacks.html

  • 8/18/2019 Exception Handling in Java FAQS

    18/44

    18

    exception remains uncaught even after reaching bottom of the stack [ main() ] so it ispropagated to JVM and ultimately program is terminated by throwing exception [ as shown inoutput ].

    Propagating checked exception(FileNotFoundException) using throws keyword > For propagating checked exceptions method must throw exception by using throws keyword. 

    Question 21. Can a catch or finally block throwexception? Answer . Yes, catch or finally block can throw checked or unchecked exception but itmust be handled accordingly. Please refer this post for  handling checked and uncheckedexceptions. 

    http://www.javamadesoeasy.com/2015/05/throws-exception-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/throws-exception-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/throws-exception-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.htmlhttp://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.htmlhttp://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.htmlhttp://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.htmlhttp://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.htmlhttp://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.htmlhttp://www.javamadesoeasy.com/2015/05/throws-exception-in-java.html

  • 8/18/2019 Exception Handling in Java FAQS

    19/44

    19

    Question 22. Why shouldn’t you use Exception forcatching all exceptions in java? Answer . Catching Exception rather than handling specific exception can be vulnerableto our application. Multiple catch blocks must be used to catch specific exceptions, becausehandling specific exception gives developer the liberty of taking appropriate action anddevelop robust application. 

    Question 23. What is Difference between multiplecatch block and multi catch syntax? Answer .

    multiple catch block   multi catch syntax 

    1  multiple catch blocks were introduced inprior versions of Java 7 and does notprovide any automatic resourcemanagement.

    multi catch syntax was introduced in java 7 for improvements in multipleexception handling which helps inautomatic resource management. 

    Here is the syntax for writing multiplecatch block > 

    try{ 

    //code . . . . .}catch(IOException ex1){ //code . . . . . } catch(SQLException ex2){ //code . . . . . }

    Here is the multi catch syntax > 

    try{ 

    //code . . . . .}catch(IOException | SQLExceptionex){ //code . . . . .}

    We could separate different exceptionsusing pipe ( | ) 

    3  For catching IOException andSQLException we need to write two catchblock like this > 

    with the help of multi catch syntax we cancatch IOException and SQLException inone catch block using multi catch syntaxlike this > 

    http://www.javamadesoeasy.com/2015/05/multiple-catch-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/multiple-catch-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/multiple-catch-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/multiple-catch-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/multiple-catch-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/catch-block-and-automatic-resource.htmlhttp://www.javamadesoeasy.com/2015/05/catch-block-and-automatic-resource.htmlhttp://www.javamadesoeasy.com/2015/05/multiple-catch-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/multiple-catch-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/multiple-catch-block-in-java.html

  • 8/18/2019 Exception Handling in Java FAQS

    20/44

    20

    4  When multiple catch blocks are used ,first catch block could be subclass of

    Exception class handled in following catchblocks like this > IOException is subclass of Exception.

     

    If Multi catch syntax is used to catchsubclass and its superclass than

    compilation error  will be thrown. IOException and Exception in multi catch

    syntax will cause compilation error “Theexception IOException is already caughtby the alternative Exception”. 

    Solution > We must use only Exception to catch itssubclass like this > 

  • 8/18/2019 Exception Handling in Java FAQS

    21/44

  • 8/18/2019 Exception Handling in Java FAQS

    22/44

    22

    public class ExceptionTest { 

    void method(Exception e){ System.out.println(e+" caught in Exception method"); 

    } void method(ArithmeticException ae){ 

    System.out.println(ae+" caught in ArithmeticException method"); 

    public static void main(String[] args) { 

    ExceptionTest obj=new ExceptionTest(); obj.method(new ArithmeticException()); obj.method(new IOException()); 

    /* OUTPUTjava.lang.ArithmeticException caught in ArithmeticException method java.io.IOException caught in Exception method 

    */ 

    Question 25. Mention few exception handling bestpractices ?

     

    Answer .

      Throw exceptions when the method cannot handle the exception, and more

    importantly, must be handled by the caller .

    Example -

    In Servlets - doGet() and doPost() throw ServletException or IOException in certaincircumstances where the request could not be read correctly. Neither of these methods arein a position to handle the exception, but the container is (which generally results in the 404error page in most cases). 

      Bubble the exception if the method cannot handle it. This is a corollary ofthe above point, but applicable to methods that must catch the exception. If thecaught exception cannot be handled correctly by the method, then it is

    preferable to bubble it.

      Throw the exception right away. If an exception scenario is encountered, thenit is a good practice to throw an exception indicating the original point of failure,instead of attempting to handle the failure via error codes, until a point deemedsuitable for throwing the exception. In other words, attempt to minimize mixingexception handling with error handling.

    http://www.javamadesoeasy.com/2015/05/throw-exception-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/exception-handling-exception-hierarchy.htmlhttp://www.javamadesoeasy.com/2015/05/exception-handling-exception-hierarchy.htmlhttp://www.javamadesoeasy.com/2015/05/exception-handling-exception-hierarchy.htmlhttp://www.javamadesoeasy.com/2015/05/exception-handling-exception-hierarchy.htmlhttp://www.javamadesoeasy.com/2015/05/throw-exception-in-java.html

  • 8/18/2019 Exception Handling in Java FAQS

    23/44

    23

      Either log the exception or bubble it, but don't do both. Logging anexception often indicates that the exception stack has been completelyunwound, indicating that no further bubbling of the exception has occurred.Hence, it is not recommended to do both at the same time, as it often leads to afrustrating experience in debugging.

      Application should not try to catch Error  - Because, in most of casesrecovery from an Error is almost impossible. So, application must be allowed toterminate.

    Example> Let’s say errors like OutOfMemoryError and StackOverflowError occur and are caught thenJVM might not be able to free up memory for rest of application to execute, so it will bebetter if application don’t catch these errors and is allowed to terminate. 

    Read : Complete list of  Exception handling best practices and guidelines for usingexceptions in java 

    Question 26. Difference between Final, Finally andFinalize? Answer .

    f inal   f inal 

    ly  

    f inal ize  

    1  final can be applied to variable, method andclass in java. 

    finally is ablock. 

    finalize is a method. 

    2.1) Final variab le  final memberVariable final local variablefinal static variable

    Final memberVariable of class must be initialized

    at time of declaration, once initialized finalmemberVariable cannot be assigned a new value. Final variables are called constants in java. 

    class FinalTest { final int x=1; //memberVariable/instanceVariable  

    If constructor is defined then final memberVariablecan be initialized in constructor but once initializedcannot be assigned a new value. 

    class FinalTest { 

    final int x; //memberVariable/instanceVariable 

    FinalTest() { 

    try or  try-catch block canbefollowedby finallyblock > 

    try-finallyblock, or  

    try{ //Code tobe enclosedin try-finallyblock 

    }finally{ 

    }

    try-catch-finally

    block. 

    finalize method iscalled before garbagecollection by JVM,finalize method iscalled for any cleanupaction that may berequired beforegarbage collection.

    /** Copyright (c),AnkitMittalJavaMadeSoEasy.com */ 

    @Override protected void finalize()throws Throwable { try {

     

    System.out.println("infinalize() method, " 

    +

    "doing cleanupactivity"); 

    http://www.javamadesoeasy.com/2015/05/javalangerror-in-exception-handling-in.htmlhttp://www.javamadesoeasy.com/2015/05/javalangerror-in-exception-handling-in.htmlhttp://www.javamadesoeasy.com/2015/05/javalangerror-in-exception-handling-in.htmlhttp://www.javamadesoeasy.com/2015/05/exception-handling-best-practices-and.htmlhttp://www.javamadesoeasy.com/2015/05/exception-handling-best-practices-and.htmlhttp://www.javamadesoeasy.com/2015/05/exception-handling-best-practices-and.htmlhttp://www.javamadesoeasy.com/2015/05/exception-handling-best-practices-and.htmlhttp://www.javamadesoeasy.com/2015/05/final-keyword-in-java-20-salient.htmlhttp://www.javamadesoeasy.com/2015/05/finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/finalize-method-in-java-10-salient.htmlhttp://www.javamadesoeasy.com/2015/05/finalize-method-in-java-10-salient.htmlhttp://www.javamadesoeasy.com/2015/05/final-keyword-in-java-20-salient.htmlhttp://www.javamadesoeasy.com/2015/05/final-keyword-in-java-20-salient.htmlhttp://www.javamadesoeasy.com/2015/05/finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/finalize-method-in-java-10-salient.htmlhttp://www.javamadesoeasy.com/2015/05/finalize-method-in-java-10-salient.htmlhttp://www.javamadesoeasy.com/2015/05/try-catch-finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/try-catch-finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/try-catch-finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/try-catch-finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/try-catch-finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/try-catch-finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/finalize-method-in-java-10-salient.htmlhttp://www.javamadesoeasy.com/2015/05/finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/final-keyword-in-java-20-salient.htmlhttp://www.javamadesoeasy.com/2015/05/finalize-method-in-java-10-salient.htmlhttp://www.javamadesoeasy.com/2015/05/finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/final-keyword-in-java-20-salient.htmlhttp://www.javamadesoeasy.com/2015/05/exception-handling-best-practices-and.htmlhttp://www.javamadesoeasy.com/2015/05/exception-handling-best-practices-and.htmlhttp://www.javamadesoeasy.com/2015/05/javalangerror-in-exception-handling-in.html

  • 8/18/2019 Exception Handling in Java FAQS

    24/44

    24

    x = 1; //final memberVariable can beinitialized in constructor. 

    } } 

    Final local variable can be left uninitialized attime of declaration and can be initialized later, butonce initialized cannot be assigned a new value. 

    class FinalTest { void method(){

    final int x; //uninitialized at time ofdeclaration 

    x=1; }

    Final static variable of class must be initialized attime of declaration or can be initialized in staticblock, once initialized final static variable cannotbe assigned a new value. 

    If static block is defined then final static variablecan be initialized in static block, once initializedfinal static variable cannot be assigned a newvalue. 

    class FinalTest { final static int  x ; //static variable static{ //static block 

     x =1; } 

    2.2) Final method  Final method cannot be overridden, any attemptto do so will cause compilation error . 

    Runtime polymorphism is not applicable on finalmethods because they cannot be inherited.

    2.3) Final class  Final class cannot be extended, any attempt to doso will cause compilation error . 

    try{ //Code tobeenclosedin try-catch-

    finallyblock 

    }catch(Exception e){ }finally{ } 

    f inal ly

    b lock

    can canonly

    exist iftry ortry-catchblock isthere,finallyblockcan’t beusedalone in

     java. 

    f inal ly

    b lock is

    not

    executed

    in

    fo l lowing

    scenarios

    >  

    finally isnotexecutedwhenSystem.exit is called. if in caseJVMcrashes because ofsome java.util.Er 

    ror . 

    } catch (Throwablethrowable) { 

    throw throwable; 

    } } 

    finalize() method isdefined in java.lang.Object 

    http://www.javamadesoeasy.com/2015/05/javalangerror-in-exception-handling-in.htmlhttp://www.javamadesoeasy.com/2015/05/javalangerror-in-exception-handling-in.htmlhttp://www.javamadesoeasy.com/2015/05/javalangerror-in-exception-handling-in.htmlhttp://www.javamadesoeasy.com/2015/05/javalangerror-in-exception-handling-in.htmlhttp://www.javamadesoeasy.com/2015/05/javalangerror-in-exception-handling-in.htmlhttp://www.javamadesoeasy.com/2015/05/javalangerror-in-exception-handling-in.html

  • 8/18/2019 Exception Handling in Java FAQS

    25/44

    25

    3  -  finallyblock canonly exist iftry or try-catch blockis there,finallyblock can’t

    be usedalone in java. 

    We can force earlygarbagecollection in java by using followingmethods > System.gc();Runtime.getRuntime().gc(); 

    System.runFinalization();Runtime.getRuntime().runFinalization(); 

    4  -  finally isalwaysexecutedirrespective ofexceptionthrown. 

    If any uncaughtexception is throwninside finalize method -

     

    exception is ignored,thread is terminatedandobject is discarded. 

    Note : Any exceptionthrown by the finalizemethod causes thefinalization of thisobject to be halted, butis otherwise ignored. 

    5  -  Currentlyexecutingthread

    calls finallymethod. 

    JVM does notguarantee which

    daemon  thread will

    invoke the finalizemethod for an object. 

    6  final is a keyword in java.  finally Is akeyword in java. 

    finalize is not akeyword in java. 

    EXCEPTIONS - Top 60 interview questions and answers in java forfresher and experienced - detailed explanation with diagrams Set-1> Q1- Q25 

    http://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.htmlhttp://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.htmlhttp://www.javamadesoeasy.com/2015/03/daemon-threads-12-salient-features-of.htmlhttp://www.javamadesoeasy.com/2015/03/what-is-thread-in-java.htmlhttp://www.javamadesoeasy.com/2015/03/what-is-thread-in-java.htmlhttp://www.javamadesoeasy.com/2015/03/what-is-thread-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/exceptions-top-60-interview-questions_16.htmlhttp://www.javamadesoeasy.com/2015/05/exceptions-top-60-interview-questions_16.htmlhttp://www.javamadesoeasy.com/2015/05/exceptions-top-60-interview-questions_16.htmlhttp://www.javamadesoeasy.com/2015/05/exceptions-top-60-interview-questions_16.htmlhttp://www.javamadesoeasy.com/2015/05/exceptions-top-60-interview-questions_16.htmlhttp://www.javamadesoeasy.com/2015/05/exceptions-top-60-interview-questions_16.htmlhttp://www.javamadesoeasy.com/2015/05/exceptions-top-60-interview-questions_16.htmlhttp://www.javamadesoeasy.com/2015/03/what-is-thread-in-java.htmlhttp://www.javamadesoeasy.com/2015/03/daemon-threads-12-salient-features-of.htmlhttp://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.html

  • 8/18/2019 Exception Handling in Java FAQS

    26/44

    26

    Question 26. Output question 1 

    public class MyClass { static String str = "a"; public static void main(String[] args) { 

    new MyClass().method1(); 

    System.out.println(str); 

    void method1() { 

    try { 

    method2(); } catch (Exception e) { 

    str += "b"; } 

    void method2() throws Exception { try{ 

    method3(); str += "c"; 

    }catch(Exception e){ 

    throw new Exception(); 

    }finally{ 

    str += "d"; } method3(); str += "e"; 

    } void method3() throws Exception {

     

    throw new Exception(); 

    Answer . adb 

    Question 27. Output question 2/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */ public class ExceptionTest { 

    public static void main(String[] args) {  m(); //call recursive method m()

     

    System.out.println("Code after exception handling"); } 

    static void m() { try { 

     m(); } catch (StackOverflowError e) { 

    e.printStackTrace(); 

  • 8/18/2019 Exception Handling in Java FAQS

    27/44

    27

    Answer . method m() calls itself recursively so StackOverflowError  will be thrown. 

    Output=java.lang.StackOverflowError

     

    at ExceptionTest.m(ExceptionTest.java:10) 

    . . 

    Code after exception handling 

    Question 28. Output question 3/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */

     

    public class ExceptionTest { 

    public static void main(String[] args) { 

    int i=10/0;System.out.println("Did this line execute?"); 

    } } 

    Answer . int i=10/0; will throw ArithmeticException Output = Exception in thread "main" java.lang.ArithmeticException: / by zero 

    At ExceptionTest.main(ExceptionTest.java:4) 

    Question 29. Output question 4 public class ExceptionTest {

     

    public static void main(String[] args) { 

    try{  int i=10/0; 

    }catch(Exception e){ System.out.println("Exception handled properly in catch block"); 

    }System.out.println("Code after exception handling"); 

    Answer .int i=10/0; will throw ArithmeticException, Exception is superclass of

     ArithmeticException, so catch block will handle ArithmeticException 

    http://www.javamadesoeasy.com/2015/05/javalangerror-in-exception-handling-in.htmlhttp://www.javamadesoeasy.com/2015/05/javalangerror-in-exception-handling-in.htmlhttp://www.javamadesoeasy.com/2015/05/javalangerror-in-exception-handling-in.htmlhttp://www.javamadesoeasy.com/2015/05/javalangerror-in-exception-handling-in.html

  • 8/18/2019 Exception Handling in Java FAQS

    28/44

    28

    Output=Exception handled properly

     

    Code after exception handling 

    finally  related output questions > 

    Question 30. Output question 5 public class ExceptionTest {

     

    public static void main(String[] args) { 

    try{ int i=10/0; //will throw ArithmeticException

     

    }catch(ArithmeticException e){ 

    System.out.println("ArithmeticException handled in catch block"); } finally{ 

    System.out.println("finally block executed");} System.out.println("code after try-catch-finally block"); 

    Answer . int i=10/0; will throw ArithmeticException, Exception is superclass of ArithmeticException, so catch block will handle ArithmeticException and finally is alwaysexecuted. 

    OUTPUT = 

    ArithmeticException handled in catch block 

    finally block executed code after try-catch-finally block 

    Question 31. Output question 6 public class ExceptionTest {

     

    public static void main(String[] args) { 

    try{ 

    System.out.println("in try block"); System.exit(0);

     

    }finally{ System.out.println("finally block executed");

    Answer . finally block is not executed when System.exit is called 

    OUTPUT = 

    in try block 

    http://www.javamadesoeasy.com/2015/05/try-catch-finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/try-catch-finally-block-in-java.html

  • 8/18/2019 Exception Handling in Java FAQS

    29/44

    29

    Question 32. Output question 7 

    public class ExceptionTest { 

    public static void main(String[] args) {try{ 

    int i=10/0; }catch(IndexOutOfBoundsException e){

     

    System.out.println("IndexOutOfBoundsException handled in catchblock");

     

    } finally{ 

    System.out.println("finally block executed");} 

    System.out.println("code after try-catch-finally block"); } 

    Answer . int i=10/0; will throw ArithmeticException,IndexOutOfBoundsException is not super class of ArithmeticException, so catch block won’tbe able to handle ArithmeticException but finally is always executed. 

    OUTPUT = finally block executed Exception in thread "main" java.lang.ArithmeticException: / by zero 

    at ExceptionTest.main(ExceptionTest.java:4) 

    Question 33. Output question 8 public class ExceptionTest { 

    public static void main(String[] args) { 

    System.out.println("method return -> "+ m()); } 

    static String m(){ try{ 

    int i=10/0; 

    }catch(ArithmeticException e){ return "catch";

     

    }finally{ 

    return "finally";} 

    } } 

    Answer . In above program, i=10/0 will throw ArithmeticException and enter catchblock to return "catch", but ultimately control will enter f inally block to return "finally". 

    OUTPUT = 

    http://www.javamadesoeasy.com/2015/05/finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/finally-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/finally-block-in-java.html

  • 8/18/2019 Exception Handling in Java FAQS

    30/44

    30

    method return -> finally 

    Multiple exception handling  related output

    questions > 

    Question 34. Output question 9. Will this program compile? public class ExceptionTest { 

    public static void main(String[] args) { 

    try{ int i=10/0;

    }catch(ArithmeticException ae){ 

    System.out.println("Exception handled - ArithmeticException"); 

    }catch(RuntimeException re){ 

    System.out.println("Exception handled - RuntimeException"); }catch(Exception e){ 

    System.out.println("Exception handled - Exception"); }

    Answer . Yes, program will compile successfully. In the above above > 

    i=10/0 will throw ArithmeticException and will be handled in first catch block. 

    ArithmeticException has been used in first catch block RuntimeException has been used in second catch block Exception has been used in third catch block 

    Exception is superclass of RuntimeException andRuntimeException is superclass of ArithmeticException. 

    OUTPUT = Exception handled - ArithmeticException

     

    Question 35. Output question 10 Will this program compile?

     

    public class ExceptionTest { public static void main(String[] args) { 

    try{ 

    int i=10/0;}catch(Exception e){

     

    System.out.println("Exception handled - RuntimeException"); }catch(ArithmeticException ae){ 

    http://www.javamadesoeasy.com/2015/05/multiple-catch-block-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/multiple-catch-block-in-java.html

  • 8/18/2019 Exception Handling in Java FAQS

    31/44

    31

    System.out.println("Exception handled - ArithmeticException"); }

    } } 

    Answer . No, program will not compile. Exception is superclass of ArithmeticException. Exception classhandled in starting catch block must be subclass of Exception class handled in followingcatch blocks (otherwise we will face compilation error). 

    In above program we will compilation error  at line 10 

    Question 36. Output question 11 

    public class MyClass { 

    static String s = ""; 

    public static void main(String[] args) { //try-catch-finally try { 

    throw new Exception(); 

    } catch (Exception e) { 

    //1st nested try-catch-finally try { 

    //2nd nested try-catch-finally try { 

    throw new Exception(); 

    } catch (Exception ex) { 

    s += "a"; } finally{ 

    s += "b"; } throw new Exception(); 

    } catch (Exception x) { s += "c"; 

    } finally { 

    s += "d"; } 

    } finally { s += "e"; 

  • 8/18/2019 Exception Handling in Java FAQS

    32/44

    32

    System.out.println(s); } 

    Answer . OUTPUT =

     

    abcde 

    Question 37. Output question 12 

    Answer . Exception is thrown at line 14, at that time value of str is “abc” Output=Exception in thread "main" java.lang.NullPointerException

     

    at MyClass.method(MyClass.java:21) 

    at MyClass.main(MyClass.java:14) 

    Question 38. Output question 13 

    will this program compile? 

  • 8/18/2019 Exception Handling in Java FAQS

    33/44

    33

    Answer . Yes, program will compile because UserDefinedException is

    RuntimeException and we are free not to handle Runtime exceptions. 

    Output= Exception in thread "main" UserDefinedException: user defined exception

     

    at UserDefinedExceptionTest.main(UserDefinedExceptionTest.java:16) 

    Multi catch syntax  related outputquestions > 

    Question 39. Output question 14 

    will this program compile? import java.io.IOException; /** Copyright (c), AnkitMittal JavaMadeSoEasy.com */ public class ExceptionTest {

     

    public static void main(String[] args) { 

    try{ 

    throw new IOException(); }catch(IOException | Exception ex){ 

    System.out.println(ex + " handled "); 

    }} 

    Answer . No, program will not compile. Multi catch syntax have been used in above program,IOException is subclass of Exception. if multi catch syntax is used to catch subclass and its superclass than compilation error  willbe thrown. IOException and Exception in multi catch syntax will cause compilation error “Theexception IOException is already caught by the alternative Exception”. 

    http://www.javamadesoeasy.com/2015/05/catch-block-and-automatic-resource.htmlhttp://www.javamadesoeasy.com/2015/05/catch-block-and-automatic-resource.html

  • 8/18/2019 Exception Handling in Java FAQS

    34/44

    34

    Solution > We must use only Exception to catch its subclass like this > 

    Propagating checked and uncheckedexceptions related output questions > 

    Question 40. Output question 15 

    public class ExceptionTest { public static void main(String[] args) { 

     method1(); System.out.println("after calling m()"); 

    static void method1(){  method2(); 

    static void method2(){ 

     method3(); } 

    static void method3(){ throw new NullPointerException();

     

    http://www.javamadesoeasy.com/2015/05/exception-propagation-in-java-deep.htmlhttp://www.javamadesoeasy.com/2015/05/exception-propagation-in-java-deep.htmlhttp://www.javamadesoeasy.com/2015/05/exception-propagation-in-java-deep.htmlhttp://www.javamadesoeasy.com/2015/05/exception-propagation-in-java-deep.html

  • 8/18/2019 Exception Handling in Java FAQS

    35/44

    35

    Answer . unchecked  exceptions are automatically propagated in java. 

    Question 41. Output question 16 public class ExceptionTest { 

    public static void main(String[] args) 

    throws FileNotFoundException { 

     method1(); System.out.println("after calling m()"); 

    static void method1() throws FileNotFoundException{  method2(); 

    static void method2() throws FileNotFoundException{ 

     method3(); 

    http://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.htmlhttp://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.htmlhttp://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.htmlhttp://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.html

  • 8/18/2019 Exception Handling in Java FAQS

    36/44

    36

    static void method3() throws FileNotFoundException{ 

    throw new FileNotFoundException(); } 

    Answer . For  propagating checked exceptions method must throw exception byusing throws keyword. 

    Question 42. Output question 17 

    http://www.javamadesoeasy.com/2015/05/exception-propagation-in-java-deep.htmlhttp://www.javamadesoeasy.com/2015/05/exception-propagation-in-java-deep.htmlhttp://www.javamadesoeasy.com/2015/05/exception-propagation-in-java-deep.htmlhttp://www.javamadesoeasy.com/2015/05/exception-propagation-in-java-deep.htmlhttp://www.javamadesoeasy.com/2015/05/throws-exception-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/throws-exception-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/throws-exception-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/throws-exception-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/exception-propagation-in-java-deep.html

  • 8/18/2019 Exception Handling in Java FAQS

    37/44

    37

    Answer . Compilation of program will fail at line 21 because for propagating checkedexceptions method must throw exception by using throws keyword. 

    try-with-resource related output questions> 

    Question 43. Output question 18 import java.io.FileInputStream;

     

    import java.io.IOException; import java.io.InputStream; /** Copyright (c), AnkitMittal JavaMadeSoEasy.com * Main class */ public class TryWithResourseTest {

     

    public static void main(String[] args) throws IOException { 

    try (InputStream inputStream = new FileInputStream("c:/txtFile.txt")) { 

    //code... } 

    } } 

    Answer .  Above program will execute properly provided file is found at specifieddirectory. In java 7, using Try-with-resources we need not to write explicit code for closingfile. 

    Now, question comes why we need not to close file when we are usingTry-with-resources? Because FileInputStream implements java.lang.AutoCloseable interface(AutoCloseable interface’s close method automatically closes resources which are

    no longer needed.) 

    http://www.javamadesoeasy.com/2015/05/throws-exception-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/throws-exception-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/throws-exception-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/try-with-resources-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/try-with-resources-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/try-with-resources-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/try-with-resources-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/try-with-resources-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/throws-exception-in-java.html

  • 8/18/2019 Exception Handling in Java FAQS

    38/44

    38

    Question 44. Output question 19 

    import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; 

    /** Copyright (c), AnkitMittal JavaMadeSoEasy.com 

    * Main class */ 

    public class TryWithResourseTest { 

    public static void main(String[] args) throws IOException { 

    try (InputStream inputStream = new FileInputStream("c:/txtFile.txt") ; InputStream bInputStream = new BufferedInputStream(inputStream)

    ) { //code...

     

    } } 

    Answer .  Above program will execute properly provided file is found at specifieddirectory, Try-with-resources allows us to use multiple resources inside it, all that we needto do is separate resources by semicolon (;) 

    throw  and throws related output questions> 

    Question 45. Output question 20 import java.io.FileNotFoundException; public class ExceptionTest {

     

    public static void main(String[] args) { 

     m(); System.out.println("after calling m()"); 

    } static void m(){ 

    throw new FileNotFoundException(); 

    Answer . If checked Exception is not handled either by try-catch or throws, we will facecompilation error. 

    http://www.javamadesoeasy.com/2015/05/throw-exception-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/throws-exception-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/throws-exception-in-java.htmlhttp://www.javamadesoeasy.com/2015/05/throw-exception-in-java.html

  • 8/18/2019 Exception Handling in Java FAQS

    39/44

    39

    Question 46. Output question 21 

    import java.io.FileNotFoundException; /** Copyright (c), AnkitMittal JavaMadeSoEasy.com */ public class ExceptionTest { 

    public static void main(String[] args) { 

     m(); 

    System.out.println("after calling m()"); } 

    static void m(){ 

    try { throw new FileNotFoundException(); 

    } catch (FileNotFoundException e) { System.out.println("FileNotFoundException handled in try-catch

    block"); } 

    Answer . In above program, We throwed FileNotFoundException (checkedexception) by using throw keyword and handled it in try-catch block. 

    OUTPUT = 

    FileNotFoundException handled in try-catch block 

    after calling m() 

    Question 47. Output question 22 import java.io.FileNotFoundException;

     

    /** Copyright (c), AnkitMittal JavaMadeSoEasy.com */ public class ExceptionTest { 

    public static void main(String[] args) { 

    try {  m (); 

    } catch (FileNotFoundException e) { System.out.println("FileNotFoundException handled in try-catch

    block"); } 

    System.out.println("after calling m()"); } 

    static void m() throws FileNotFoundException{ throw new FileNotFoundException();

     

    Answer . In the above program, method m() propagated exception to calling method(i.e. main method) using throws. 

    OUTPUT = FileNotFoundException handled in try-catch block

     

    http://www.javamadesoeasy.com/2015/05/exception-propagation-in-java-deep.htmlhttp://www.javamadesoeasy.com/2015/05/exception-propagation-in-java-deep.htmlhttp://www.javamadesoeasy.com/2015/05/exception-propagation-in-java-deep.htmlhttp://www.javamadesoeasy.com/2015/05/exception-propagation-in-java-deep.htmlhttp://www.javamadesoeasy.com/2015/05/exception-propagation-in-java-deep.html

  • 8/18/2019 Exception Handling in Java FAQS

    40/44

    40

    after calling m() 

    Question 48. Output question 23 

    Answer . We throw NullPointerException (unChecked exception) and didn’t handled it, no compilationerror  was thrown.We need not to handle unChecked exception either by catching it or throwing it.  

    Output - 

    Question 49. Output question 24 

    Answer . We need to handle checked exception either by catching it or throwing itfurther, if not handled we will face compilation error at line 8. 

    Question 50. Output question 25 

    import java.io.IOException; import java.sql.SQLException; /** Copyright (c), AnkitMittal JavaMadeSoEasy.com */ public class ExceptionTest {

     

  • 8/18/2019 Exception Handling in Java FAQS

    41/44

    41

    public static void main(String[] args) { 

    try { 

     m(); System.out.print("a"); 

    } catch (Exception e) { System.out.print("b"); 

    } finally{ 

    System.out.print("c"); } 

    static void m() throws IOException, SQLException{ int i=1; if(i==1) 

    throw new IOException(); 

    else 

    throw new SQLException(); 

    } } 

    Answer . 

    Output = bc

     

    Question 51. Output question 26 

    class SuperClass{ 

    void method() throws NullPointerException{ 

    System.out.println("superClass method"); } 

    } class SubClass extends SuperClass{ 

    void method() throws RuntimeException{ System.out.println("SubClass method"); 

    } /** Copyright (c), AnkitMittal JavaMadeSoEasy.com * Main class */

     

    public class ExceptionTest { 

    public static void main(String[] args) { SuperClass obj=new SubClass();

     

    obj.method(); } 

    Answer . If superclass method does not throw  /declare any except ion -  overridden method of subclass can declare/ th row any unchecked /Run timeExcep tion (super c las s o r subclass)  

    RuntimeException is superclass of NullPointerException. 

    Output = 

    http://www.javamadesoeasy.com/2015/05/throwdeclare-checked-and-unchecked.htmlhttp://www.javamadesoeasy.com/2015/05/throwdeclare-checked-and-unchecked.htmlhttp://www.javamadesoeasy.com/2015/05/throwdeclare-checked-and-unchecked.html

  • 8/18/2019 Exception Handling in Java FAQS

    42/44

    42

    SubClass method 

    Question 52. Output question 27 

    Answer . If superclass method does not throw  /declare any except ion -overridden method of subclass cannot declare/ th row  any checked except ion  

     Any attempt to throw checked exception in overridden method of subclass will causecompilation error . 

    Question 53. Output question 28 

    import java.io.FileNotFoundException; import java.io.IOException; 

    class SuperClass{ 

    void method() throws IOException{ System.out.println("superClass method"); 

    class SubClass extends SuperClass{ 

    void method() throws FileNotFoundException{ System.out.println("SubClass method"); 

    /** Copyright (c), AnkitMittal JavaMadeSoEasy.com 

    * Main class */ 

    public class ExceptionTest { public static void main(String[] args) throws Exception { 

    SuperClass obj=new SubClass(); 

    obj.method(); 

    Answer . If superclass method throws/declare checked  / compi leTime  except ion - overridden method of subclass can declare/ th row  narrower (subclassof) checked except ion  

  • 8/18/2019 Exception Handling in Java FAQS

    43/44

    43

    IOException is superclass of FileNotFoundException. Output = SubClass method

     

    Question 54. Output question 29 

    Answer . If superclass method throws/declare checked  / compi leTime  except ion - overriddenmethod of subclass cannot declare/ th row  broader (superclass of) checkedexcept ion  

     Any attempt to throw broader (superclass of) checked exception in overridden method ofsubclass will cause compilation error . Exception is superclass of IOException. 

    Question 55. Output question 30 import java.io.IOException;

     

    class SuperClass{ 

    void method() throws IOException{ System.out.println("superClass method"); 

    class SubClass extends SuperClass{ 

    void method() throws NullPointerException{ System.out.println("SubClass method");

     

    /** Copyright (c), AnkitMittal JavaMadeSoEasy.com 

    * Main class */ 

    public class ExceptionTest { public static void main(String[] args) throws Exception { 

    SuperClass obj=new SubClass(); obj.method(); 

  • 8/18/2019 Exception Handling in Java FAQS

    44/44