Exception handling multiple choice interview questions and answers in java

Exception handling in method overriding in java

  • Defining multiple methods with same name and same signature in super class and sub class known as method overriding.
  • When Overriding a method there is a chance of having statements which may cause exceptions so we need to handle those inside method.
  • Otherwise simply we can give responsibility of handling exceptions to calling method.
  • We can give the responsibility of handling exceptions of a method to calling place by using throws keyword in java.
  • Now we are going to discuss about exception handling in method overriding in java.
  • When am method is overridden in sub class and super class method having throws exception. Then we have some scenarios to discuss.



1.Super class method not throwing any exceptions.
2.Super class method  throws exceptions.


1.Super class method  Not throwing any exceptions.
  • When super class method not throws ant exception,
  • We can add throws unchecked exception in sub class overridden method.
  • We can not add throws checked exception.

Program #1: When super class method does not have any throws exception then we can add throws un checked exception in subclass overridden method.

  1. package exceptionhandlingmethodoverridingjava;
  2. public class Super {
  3.  
  4.     /**
  5.      * @author www.instanceofjava.com
  6.      * @category throws in method overriding java
  7.      */
  8.     
  9.     
  10. public void show(){
  11.         
  12.  System.out.println("Super class show() method");
  13.  
  14. }
  15.  
  16. }

  1. package exceptionhandlingmethodoverridingjava;
  2. public class Sub extends Super {
  3.  
  4. /**
  5. * @author www.instanceofjava.com
  6. * @category throws in method overriding java
  7. */
  8.     
  9. public void show() throws NullPointerException{
  10.         
  11.         System.out.println("Sub class show() method");
  12.  }

  13. public static void main(String[] args) {
  14.  
  15.    Sub obj = new Sub();
  16.     obj.show();
  17.  
  18. }
  19.  
  20. }
Output:

  1. Sub class show() method


Program #2: When super class method does not have any throws exception then we can not add throws checked exception in subclass overridden method.

  1. package exceptionhandlingmethodoverridingjava;
  2. public class Super {
  3.  
  4.     /**
  5.      * @author www.instanceofjava.com
  6.      * @category throws in method overriding java
  7.      */
  8.     
  9.     
  10. public void show(){
  11.         
  12.  System.out.println("Super class show() method");
  13.  
  14. }
  15.  
  16. }

Exception handling in method overriding throws



2.Super class method  throws exceptions.

  • If super class method throws checked exceptions sub class overridden method can throw same exception , sub class exception or no exception but can not declare parent exception.
  • If super class method throws unchecked exceptions then no rules.


Program #3: When super class method  throws checked exception then we can add throws  checked exception in subclass overridden method.

  1. package exceptionhandlingmethodoverridingjava;
  2. public class Super {
  3.  
  4.     /**
  5.      * @author www.instanceofjava.com
  6.      * @category throws in method overriding java
  7.      */
  8.     
  9.     
  10. public void show() throws IOException{
  11.         
  12.  System.out.println("Super class show() method");
  13.  
  14. }
  15.  
  16. }

  1. package exceptionhandlingmethodoverridingjava;
  2. public class Sub extends Super {
  3.  
  4. /**
  5. * @author www.instanceofjava.com
  6. * @category throws in method overriding java
  7. */
  8.     
  9. public void show() throws IOException{
  10.         
  11.         System.out.println("Sub class show() method");
  12.  }

  13. public static void main(String[] args) {

  14.  
  15.    Sub obj = new Sub();
  16.  
  17.  try {
  18.             obj.show();
  19. } catch (IOException e) {
  20.          
  21.             e.printStackTrace();
  22. }
  23.  
  24. }
  25.  
  26. }
Output:

  1. Sub class show() method

Program #4: When super class method  throws unchecked exception then we can not add throws  checked exception in subclass overridden method.

  1. package exceptionhandlingmethodoverridingjava;
  2. public class Super {
  3.  
  4.     /**
  5.      * @author www.instanceofjava.com
  6.      * @category throws in method overriding java
  7.      */
  8.     
  9.     
  10. public void show() throws ArithmeticException{
  11.         
  12.  System.out.println("Super class show() method");
  13.  
  14. }
  15.  
  16. }


throws in method overriding java


Program #5: When super class method  throws checked exception then we can not add throws its  parent exception in subclass overridden method.

  1. package exceptionhandlingmethodoverridingjava;
  2. public class Super {
  3.  
  4.     /**
  5.      * @author www.instanceofjava.com
  6.      * @category throws in method overriding java
  7.      */
  8.     
  9.     
  10. public void show() throws FileNotFoundException{
  11.         
  12.  System.out.println("Super class show() method");
  13.  
  14. }
  15.  
  16. }

  1. package exceptionhandlingmethodoverridingjava;
  2. public class Sub extends Super {
  3.  
  4. /**
  5. * @author www.instanceofjava.com
  6. * @category throws in method overriding java
  7. */
  8.     
  9. public void show() throws IOException{
  10.         
  11.         System.out.println("Sub class show() method");
  12.  }

  13. public static void main(String[] args) {

  14.  
  15. Sub obj = new Sub();
  16.  
  17. try {
  18.            obj.show();
  19. } catch (Exception e) {
  20.           
  21.             e.printStackTrace();
  22. }
  23.  
  24. }
  25.  
  26. }

Top 20 Java Exception handling interview questions and answers

1.What is an exception?


  • Exceptions are the objects representing the logical errors that occur at run time and makes JVM enters into the state of  "ambiguity".
  • The objects which are automatically created by the JVM for representing these run time errors are known as Exceptions



2.What are the differences between exception and error.

  • An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions.
  • Difference between exception and error

3.How the exceptions are handled in java

  • Exceptions can  be handled using try catch blocks.
  • The statements which are proven to generate exceptions need to keep in try block so that whenever is there any exception identified in try block that will be assigned to corresponding exception class object in catch block
  • More information about try catch finally

4.What is the super class for Exception and Error

  • Throwable.


  1. public class Exception extends Throwable implements Serializable


  1. public class Error extends Throwable implements Serializable

5.Exceptions are defined in which java package

  • java.lang.Exception

6.What is throw keyword in java?

  • Throw keyword is used to throw exception manually.
  • Whenever it is required to suspend the execution of the functionality based on the user defined logical error condition we will use this throw keyword to throw exception.
  • Throw keyword in java

7.Can we have try block without catch block

  • It is possible to have try block without catch block by using finally block
  • Java supports try with finally block
  • As we know finally block will always executes even there is an exception occurred in try block, Except System.exit() it will executes always.
  • Is it possible to write try block without catch block

8.Can we write multiple catch blocks under single try block?


exception handling interview questions and answers


9. What are unreachable blocks in java

  • The block of statements to which the control would never reach under any case can be called as unreachable blocks.
  • Unreachable blocks are not supported by java.
  • Unreachable blocks in java


unreachable block exception handling interview question



10.How to write user defined exception or custom exception in java



  1. class CustomException extends Exception { } // this will create Checked Exception
  2. class CustomException extends IOExcpetion { } // this will create Checked exception
  3. class CustomException extends NullPonterExcpetion { } // this will create UnChecked
  4. exception

11.What are the different ways to print exception message on console.

  • In Java there are three ways to find the details of the exception .
  • They are 
  1. Using an object of java.lang.Exception
  2. Using public void printStackTrace() method
  3. Using public String getMessage() method.
print exception message in java



12.What are the differences between final finally and finalize in java




13.Can we write return statement in try and catch blocks


return statement in try catch block exception handling



14. Can we write return statement in finally block



return statement in finally exception handling interview


15. What are the differences between throw and throws


  •  throw keyword used to throw user defined exceptions.(we can throw predefined exception too)
  • Using throws keyword we can explicitly provide the information about unhand-led exceptions of the method to the end user, Java compiler, JVM.
  • Throw vs throws

throw vs throws

 16.Can we change an exception of a method with throws clause from unchecked to checked while overriding it? 


  •  No. As mentioned above already
  • If super class method throws exceptions in sub class if you want to mention throws  then use  same class  or its  sub class exception.
  • So we can not change from unchecked to checked 

 17.What are the rules we need to follow in overriding if super class method throws exception ?


  •  If sub class throws checked exception super class should throw same or super class exception of this.
  • If super class method  throws checked or unchecked exceptions its not mandatory to put throws in sub class overridden method.
  • If super class method throws exceptions in sub class if you want to mention throws  then use  same class  or its  sub class exception.

 

18.What happens if we not follow above rules if super class method throws some exception.

  •  Compile time error will come.

  1. package MethodOverridingExamplePrograms;
  2. public class Super{
  3.  
  4. public void add(){
  5.  System.out.println("Super class add method");
  6. }

  7. }

  1. package MethodOverridingInterviewPrograms;
  2. public class Sub extends Super{
  3.   
  4. void add() throws Exception{ //Compiler Error: Exception Exception is not compatible with
  5. throws clause in Super.add()
  6. System.out.println("Sub class add method");

  7. }

  8. }

  1. package ExceptionHandlingInterviewPrograms;
  2. public class Super{
  3.  
  4. public void add(){
  5.  System.out.println("Super class add method");
  6. }

  7. }

  1. package ExceptionHandlingInterviewPrograms;
  2. public class Sub extends Super{
  3.   
  4. void add() throws NullPointerException{ // this method throws unchecked exception so no
  5. isuues
  6. System.out.println("Sub class add method");

  7. }

  8. }

 19. Is it possible to write multiple exceptions in single catch block


  • It is not possible prior to java 7.
  • new feature added in java 7.


  1. package exceptionsFreshersandExperienced;
  2. public class ExceptionhandlingInterviewQuestions{
  3.  
  4. /**
  5.  * @www.instanceofjava.com
  6.  **/
  7.  public static void main(String[] args) {

  8.  
  9. try {
  10.  
  11. // your code here
  12.             
  13. } catch (IOException | SQLException ex) {
  14.             System.out.println(e);
  15. }
  16.  
  17. }
  18.  
  19. }



20. What is try with resource block

  • One more interesting feature of Java 7 is try with resource 
  • In Java, if you use a resource like input or output streams or any database connection logic you always need to close it after using. 
  • It also can throw exceptions so it has to be in a try block and catch block. The closing logic  should be in finally block. This is a least the way until Java 7. This has several disadvantages:

    1.     You'd have to check if your ressource is null before closing it
    2.     The closing itself can throw exceptions so your finally had to contain another try -catch
    3.     Programmers tend to forget to close their resources

  • The solution given by using try with resource statement.

  1. try(resource-specification) 
  2. {
  3.  
  4. //use the resource
  5.  
  6. }catch(Exception e)
  7. {
  8.  
  9. //code

  10. }

  • Top 20 Java Exception handling interview questions and answers for freshers and experienced

3 different ways to print exception message in java

  • In Java there are three ways to find the details of the exception .
  • They are 
  1. Using an object of java.lang.Exception
  2. Using public void printStackTrace() method
  3. Using public String getMessage() method.

1.Using an object of java.lang.Exception

  •  An object of Exception class prints the name of the exception and nature of the exception.



Write a Java program get detailed message details using exception class object



  1. package exceptions;
  2. public class ExceptionDetails {
  3.  
  4. /**
  5.  * @www.instanceofjava.com
  6.  **/
  7.  public static void main(String[] args) {
  8.  
  9. try {
  10.  
  11. int x=1/0;
  12.             
  13. } catch (Exception e) {
  14.             System.out.println(e);
  15. }
  16.  
  17. }
  18.  
  19. }

 Output:


  1. java.lang.ArithmeticException: / by zero


 2.Using  public void printStackTrace() method


  • This is the method which is defined in java.lang.Throwable class and it is inherited into java.lang.Error class and java.lang.Exception class
  • This method will display the name of the exception and nature of the message and line number where exception has occurred.

Write a simple java example program to print exception message to console using printStacktrace() method



  1. package exceptions;
  2. public class ExceptionDetails {
  3.  
  4.     /**
  5.      * @www.instanceofjava.com
  6.      */
  7. public static void main(String[] args) {

  8.  
  9.  try {
  10.           int a[]= new int[1];
  11.             a[1]=12
  12.             
  13. } catch (Exception e) {
  14.    e.printStackTrace();
  15.            
  16.  }
  17. }
  18.  
  19. }

 Output:


  1. java.lang.ArrayIndexOutOfBoundsException: 1
        at exceptions.ExceptionDetails.main(ExceptionDetails.java:13)

  3.Using public String getMessage() method

  •  This is also a method which is defined in java.lang.Throwable class and it is inherited in to both java.lanf.Error and java.lang.Exception classes.
  • This method will display the only exception message


Write a Java program print exception message using getMessage() method.


  1. package exceptions;
  2. public class ExceptionDetails {
  3.  
  4.     /**
  5.      * @www.instanceofjava.com
  6.      */
  7.     public static void main(String[] args) {

  8.  
  9.         try {
  10.             int x=1/0;
  11.             
  12.         } catch (Exception e) {
  13.             System.out.println(e.getMessage());
  14.         }
  15.     }
  16.  
  17. }

 Output:


  1.  / by zero

print exception message

throw keyword in java with example

Throw keyword in java

  • Throw keyword is used to throw exception manually.
  • Whenever it is required to suspend the execution of the functionality based on the user defined logical error condition we will use this throw keyword to throw exception.
  • So we need to handle these exceptions also using try catch blocks.



 Java simple example Program to explain use of throw keyword in java


  1. package exceptions;
  2.  
  3. public class ThrowKeyword {
  4.  
  5.     
  6. public static void main(String[] args) {
  7.  
  8. try {
  9.             
  10.    throw new ArithmeticException();
  11.             
  12.             
  13. } catch (Exception e) {
  14.  
  15.    System.out.println(e);
  16.    e.printStackTrace();
  17. }
  18.  
  19. }
  20.  
  21. }

Output:



  1. java.lang.ArithmeticException
  2. java.lang.ArithmeticException
  3.     at exceptions.ThrowKeyword.main(ThrowKeyword.java:11)

Rules to use "throw" keyword in java
  • throw keyword must follow Throwable type of object.
  • It must be used only in method logic.
  • Since it is a transfer statement , we can not place statements after throw statement. It leads to compile time error Unreachable code



throw keyword in java


  •  We can throw user defined exception using throw keyword.

  1. //Custom exception
  2. package com.instanceofjavaforus;
  3. public class InvalidAgeException extends Exception {
  4.  InvaidAgeException(String msg){
  5.  super(msg);
  6.  }
  7. }
     

  1. package com.exceptions;
  2. public class ThrowDemo {

  3. public boolean isValidForVote(int age){
  4.  
  5.  try{
  6.    if(age<18){
  7.   throw new InvalidAgeException ("Invalid age for voting");
  8. }
  9.  }catch(Exception e){
  10.  System.out.println(e);
  11.  }
  12.   return false;
  13.  }
  14.  
  15. public static void main(String agrs[]){
  16.  
  17.  ThrowDemo obj= new ThrowDemo();
  18.    obj.isValidForVote(17);
  19.  
  20.   }
  21. }


 Output:


  1.  exceptions.InvalidAgeException: Invalid age for voting
  • We can throw predefined exceptions using throw keyword


  1. package com.instanceofjava;
  2.  
  3. public class ThrowKeyword{
  4. public void method(){
  5.  
  6.  try{
  7.   
  8.   throw new NullPointerException("Invalid age for voting");
  9. }
  10.  }catch(Exception e){
  11.  System.out.println(e);
  12.  }
  13.  }
  14.  
  15.   public static void main(String agrs[]){
  16.  
  17.  ThrowKeyword obj= new ThrowKeyword();
  18.  
  19.    obj.method();
  20.  
  21.   }
  22. }

 Output:


  1.  java.lang.NullPointerException: Invalid age for voting

Multiple catch blocks in java example

Is there any chance of getting multiple exception?

  • Lets see a java example programs which can raise multiple exceptions.


  1. package exceptions;
  2. public class MultipleCatchBlocks {
  3.  
  4.     /**
  5.      * @www.instanceofjava.com
  6.      */
  7.  
  8. public static void main(String[] args) {
  9.         
  10.         
  11.  int x=10;
  12.  int y=0;
  13.  
  14. try{
  15.             
  16.    int i=x/y;
  17.    int a[]=new int[2];
  18.    a[3]=12;
  19.             
  20. } catch(ArithmeticException e){
  21.             e.printStackTrace();
  22. }
  23.  
  24. }
  25.  
  26. }

Output:


  1. java.lang.ArithmeticException: / by zero
        at exceptions.MultipleCatchBlocks.main(MultipleCatchBlocks.java:15)

  •  Lets see second case:


multiple catch blocks in java




try with multiple catch blocks

  • In the 1st program there is a chance of getting two types of exceptions and we kept only one catch block with  ArithmeticException e . 
  • But there will be chance of getting ArrayIndexOutOfBoundsException too. 
  • So we need to keep multiple catch blocks in order to handle all those exceptions
  • Or else we can keep single catch block with super class Exception class object.

 




Multiple catch blocks for single try block:

 

  • One try can have multiple catch blocks 
  • Every try should and must be associated with at least one catch block.( try without catch)
  • Whenever an exception object is identified in try block and if there are multiple catch blocks then the priority for the catch block would be given based on order in which catch blocks are have been defined.
  • Highest priority would be always given to first catch block . If the first catch block can not handle the identified exception object then it considers the immediate next catch block.

Disadvantages of multiple catch blocks:
 
  •  We have to know the names of every corresponding exception class names.
  • We have to understand which statement is generating which exception class object.



Solution: 

  •  Define a single catch block so that it should be able to handle any kind of exceptions identified in the try block.
  • Exception class is the super class for all the exception classes.
  • To the reference of super class object we can assign any sub class object.

Can we have try without catch block in java

  • It is possible to have try block without catch block by using finally block
  • Java supports try with finally block
  • As we know finally block will always executes even there is an exception occurred in try block, Except System.exit() it will executes always.
  • We can place logic like connections closing or cleaning data  in finally.


Java Program to write try without catch block | try with finally block
  1. package exceptionsInterviewQuestions;
  2. public class TryWithoutCatch {
  3.  
  4.     
  5. public static void main(String[] args) {
  6.         
  7.         
  8. try {
  9.             
  10.   System.out.println("inside try block");
  11.             
  12. } finally{
  13.             
  14.             System.out.println("inside finally block");
  15. }
  16.  
  17. }
  18.  
  19. }



Output:


  1. inside try block
  2. inside finally block

  •  Finally block executes Even though the method have return type and try block returns something

Java Program to write try with finally block and try block returns some value

  1. package exceptionsInterviewQuestions;
  2.  
  3. public class TryWithFinally {
  4.  
  5. public static int method(){  
  6.   
  7.        
  8. try {
  9.             
  10.   System.out.println("inside try block");
  11.  
  12.  return 10;        
  13. } finally{
  14.             
  15.             System.out.println("inside finally block");
  16. }
  17.  
  18. }
  19.  
  20. public static void main(String[] args) {
  21.         
  22. System.out.println(method());
  23.  
  24. }
  25.  
  26. }

Output:


  1. inside try block
  2. inside finally block
  3. 10


What happens if exception raised in try block?

  • Even though exception raised in try block finally block executes.

try with finally block in java

Select Menu