Showing posts with label Exception handling interview questions with answers in java. Show all posts
Showing posts with label Exception handling interview questions with answers in java. Show all posts

Thursday, 9 February 2017

Exception Handling in method overriding in Java

     In this post, we can discuss the how exception handling in  method overriding in Java. There are some rules to handle the exception in method overriding.

Rule - 1) If super class method does not declare an exception, subclass overridden method can  not declare the checked exception.


   Example : -
                      class Parent {
                               public void display () {
                                       System.out.println("This is the super class method");
                               }

                       }


                       class Child extends parent {
                                public void display () throws FileNotFoundException {      //compile time error
                                       System.out.println("This is the overridden method");
                                }
                         
                                public static void main (String[] args) {
                                        Parent p = new Child ();
                                        p.display();
                                }
                       }

     Output : - Compile Time Error.



Rule - 2)  If super class method does not declare an exception(checked or unchecked), sub class overridden method can not declare checked  exception but declare unchecked exception.


Example : -
                   class Parent {
                               public void display () {
                                       System.out.println("This is the super class method");
                               }
                       }

                       class Child extends parent {
                                public void display () throws NullPointerException {      
                                       System.out.println("This is the overridden method");
                                }
                         
                                public static void main (String[] args) {
                                        Parent p = new Child ();
                                        p.display();
                                }
                       }
               
 Output : - This is the overridden method



Rule - 3) If the super class method declares an exception, sub class overridden method declares same exception, sub class exception or no exception but can not declare parent exception.


Example 1:-
           If the super class method declares an exception , sub class overridden method declares a same exception.
     
               class Parent {
                               public void display () throws NullPointerException {
                                       System.out.println("This is the super class method");
                               }

                       }


                       class Child extends parent {
                                public void display () throws NullPointerException {      
                                       System.out.println("This is the overridden method");
                                }
                         
                                public static void main (String[] args) {
                                        Parent p = new Child ();
                                        p.display();
                                }
                       }

The above code run successfully. And will print "This is the overridden method".

Example 2 :-
            If the super class method declares an exception , sub class overridden method declares a sub class exception .  
                       
                        class Parent {
                               public void display () throws Exception {
                                       System.out.println("This is the super class method");
                               }

                       }


                       class Child extends parent {
                                public void display () throws ArithmeticException {      
                                       System.out.println("This is the overridden method");
                                }
                         
                                public static void main (String[] args) {
                                        Parent p = new Child ();
                                        p.display();
                                }
                       }

The above code run successfully. And will print "This is the overridden method".


Example 3 :-
            If the super class method declares an exception , sub class overridden method declares no exception .

                       class Parent {
                               public void display () throws Exception {
                                       System.out.println("This is the super class method");
                               }

                       }


                       class Child extends parent {
                                public void display () {      
                                       System.out.println("This is the overridden method");
                                }
                         
                                public static void main (String[] args) {
                                        Parent p = new Child ();
                                        p.display();
                                }
                       }

The above code run successfully. And will print "This is the overridden method".

Example 4 :-  
              If the super class method declares an exception, sub class overridden method can not declares parent exception(i.e border exception).

                      class Parent {
                               public void display () throws ArithmeticException {
                                       System.out.println("This is the super class method");
                               }

                       }


                       class Child extends parent {
                                public void display () throws Exception { //Compile Time error 
                                       System.out.println("This is the overridden method");
                                }
                         
                                public static void main (String[] args) {
                                        Parent p = new Child ();
                                        p.display();
                                }
                       }

The above code can not compile, will give Compile Time Error.


Related Post:-
Exception Handling Interview questions and answers  
How to Create the Custom Exception in Java ?  

Sunday, 4 September 2016

How to Create the Custom Exception in Java ?

        In this post, we will learn how to create the custom exception in Java.  To achieve this we can create a Java custom exception class that can  extends Exception class.
        Below code is a sample example of custom or user defined exception class. In this example, if entered age value is less than or equal to 0 or greater than 100 then it will throw the exception with user defined message at the client side.


   public class InvalidAgeException extends Exception { 
              
            public InvalidAgeException(String message) { 
                      super(message);  
            } 
   }

        In the below class, the ageValidate(int age) method will throw the Runtime exception i.e InvalidAgeException when the entered age is less than or equal to 0 or greater than 100. We can provide user understandable message at the client side so user can easily understand the exception.
 
public class CustomExceptionDemo {    

         public int validateAge(int age) { 
                if (age <=0 || age > 100) { 
                      try { 
                           throw new InvalidAgeException("Entered age is not a valid age"); 
                      } catch (InvalidAgeException ex) { 
                         ex.printStackTrace();
                      }        
                } 
                return age; 
        } 

       public static void main (String[] args){ 
               CustomExceptionDemo demo = new ExceptionDemo(); 
               //int age = demo.validateAge(36); 
               int age1 = demo.validateAge(120);  // here it will throw exception.
       } 
}

Output of the above code: -

com.practice.InvalidAgeException: Entered age is not a valid age    at com.practice.CustomExceptionDemo.validateAge(CustomExceptionDemo.java:12)
    at com.practice.
CustomExceptionDemo.main(CustomExceptionDemo.java:23)


      The base Exception class has the following constructors,  we used one constructor in the above example.
 

1) Exception()
 

2) Exception (String message)
 

3) Exception (String message, Throwable cause)
 

4) Exception (Throwable cause)


Related Post: --    
Exception Handling Interview questions and answers  
How to Create Custom Immutable Class with mutable object references in Java?
Factory Design Pattern in Java
Difference between final,finalize and finally in Java

Tuesday, 3 June 2014

Java Exception Handling Interview Questions and Answers


 Exception Handling Keywords:

                  Java provides several keywords for exception handling. Let's first understand these keywords, and then we'll write a simple program to demonstrate how to use them for exception handling.

  1.  throw 
          
          We know that when an exception occurs, Java creates an exception object, and the Java runtime begins processing it to handle the exception. Sometimes, we may want to explicitly generate an exception in our code. For example, in a user authentication program, we should throw an exception if the password is null. The throw keyword is used to explicitly throw an exception, which is then handled by the Java runtime or propagated to the calling method.


   2. throws

               When a method throws an exception and does not handle it, you must use the throws keyword in the method signature to inform the caller about the exceptions that the method may throw. The calling method can either handle these exceptions using a try-catch block or propagate them to its caller by declaring the throws keyword in its own method signature. You can specify multiple exceptions in the throws clause, and it can also be used with the main() method.


  3. try-catch
           
           We use the try-catch block to handle exceptions in Java. The try block contains the code that may throw an exception, while the catch block handles the exception if one occurs. A single try block can be followed by multiple catch blocks to handle different types of exceptions. Additionally, try-catch blocks can be nested. Each catch block requires a parameter whose type must be an exception class or one of its subclasses.


  4. finally

         The finally block is optional and is used with a try block, either with or without a catch block. Since an exception can interrupt the normal flow of program execution, some resources (such as files, database connections, or network sockets) may remain open if they are not closed properly. The finally block is typically used to release these resources. It is executed regardless of whether an exception occurs or not, ensuring that cleanup code always runs.

    Let's look at the following important points:
  • You cannot have a catch or finally block without a corresponding try block.

  • A try statement must be followed by at least one catch block, a finally block, or both.

  • You cannot write any code between the try, catch, and finally blocks. Doing so results in a compile-time error. For example, you cannot place any statements between a try block and its corresponding catch block.

  • A single try block can be followed by multiple catch blocks to handle different types of exceptions.

  • try-catch blocks can be nested, just like if-else statements.

  • A try statement can have only one finally block.


      Below some questions related to try catch and finally block examples.

1) Which is the base class of all Exception classes?


            Throwable


2) Once the control switches to the catch block does it return   back to the try block to execute the balance code?
   
      No. Once the control jumps to the catch block it never returns to the try block but it goes to finally block(if present).


3) How do you get the descriptive information about the Exception occurred during the program execution?

       All the exceptions inherit a method printStackTrace() from the Throwable class. This method prints the stack trace from where the exception occurred.
   e.g       catch(Exception e){
                     Systom.out.println(e.printStackTrace());
               }


4) 
                          try{                      
                                      //some statements
                               }
                               catch(Exception e){                 
                                      System.out.println("Exception ");
                               }
                               catch(ArithmeticExcetion ex){
                                      System.out.println("AritmeticException ");
                               }
What is output?

        This code will produce a compile-time error at the second catch block. The Exception class is the superclass of all checked exceptions and most runtime (unchecked) exceptions, including ArithmeticException. Since ArithmeticException is a subclass of Exception, placing the Exception catch block before the ArithmeticException catch block makes the latter unreachable. Therefore, the Exception catch block should always be placed at the end of the catch block sequence.


5) What will be the output of the following code? 

                              try{
                                         //some statements
                              }                                                                        //line 1
                              System.out.println("end try block");
                              catch(Exception e){                                              //line 2
                                       System.out.println("Exception ");
                              }

   It will give compile-time error at line 1 and line 2 because for first line you haven't written catch or finally block & second it act as without try block.


6) 
What will be the output of the following code?

                           public int methodName(){
                                    try{
                                              //some statements
                                              return 1;
                                    }
                                    catch(Exception e){
                                              return 2;
                                    }
                                    finally{
                                              return 3;
                                    }
                          }                                               //end method
    The above method will return which value 1 or 2 or 3. also answer me with exception & without exception.

     In java finally block will execute all time except calling System.exit(). So above example it will return always 3 with exception or non-exception(not a matter).


7) What will be the output of the following code?
                                       try{
                                               int i=0; int j=1;
                                               int sum=j/i;                                             //line 1
                                               System.exit(0);                                      //line 2
                                        }
                                        catch(Exception e){
                                                e.printStackTrace();
                                        }
                                        finally{
                                                 System.out.println("finally block");
                                        }

 Output is----------------java.lang.ArithmeticException
                                                   finally block

In the above code,at line 1,it will throw exception i.e catch block will execute and followed by finaaly block execute. It never return to the line 2.



8) What will be the output of the following code?
                                        try{
                                               int sum=1/1;                                             //line 1
                                               System.out.println(sum);
                                               System.exit(0);                                        //line 2
                                        }
                                        catch(Exception e){
                                                e.printStackTrace();
                                        }
                                        finally{
                                                System.out.println("finally block");
                                        }

    In the above code finally block won't execute because it will exit in try block itself.
               output is 1.
   

9) Exception Hierarchy in java


exceptionhierarchy

Error :          
          An Error indicates that a non-recoverable condition has occurred that should not be caught. Error, a subclass of Throwable, is intended for drastic problems, such as OutOfMemoryError, which would be reported by the JVM itself.
 
Exception :
        
         An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. There are two types of Exceptions 1)Checked Exception 2) Unchecked Exception

1) Checked Exception:--

              These exceptions are the object of the Exception class or any of its subclasses except Runtime exception class.  These condition arises due to invalid input,problem with your network connectivity & problem in database. IOException,SQLException,DataAccessException,ClassNotFoundException & MalformedURLException are the Checked Exception.  This Exception is thrown when there is an error in I/O operation. In this case operation is normally terminated.

2) Unchecked Exception:--  

              These exceptions arises during run-time that occur due to invalid argument passed to method. The java compiler doesn't check the program error during compilation. e.g ArithmeticException, NumberFormatException, NullPointerException, IndexOutOfBoundsException, ClassCastException & IllegalArgumentException etc.
             


Does method can return exception ?

     Method does not return exception but it will throw an exception.


What happens when exception is thrown by main method?        
      When exception is thrown by main , Java runtime system terminates.


What is OutOfMemoryError in Java?

    
OutOfMemoryError is when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector. OutOfMemoryError in Java is a subclass of VirtualMachineError.



What is difference between ClassNotFoundException and NoClassDefFoundError?     
        ClassNotFoundException is thrown when an application tries to load in a class through its string name using:

    The forName method in class Class.
    The findSystemClass method in class ClassLoader .
    The loadClass method in class ClassLoader.

but no definition for the class with the specified name could be found.

NoClassDefFoundError
is thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found. For more details, Refer Difference between NoClassDefFoundError and ClassNotFoundException in Java



Related Post :--
1) How to create the custom exception in Java?
2) String Interview Questions and Answers
3) Difference between final,finalize and finally in Java
4) Exception Handling in method overriding in Java
5) Static Keyword and Its usage in Java
6) Factory Design Pattern in Java
7) Difference between NoClassDefFoundError and ClassNotFoundException in Java