Search

Complete reference to core java interview questions basic to advanced level : SE to Team Lead level Part - 4

Exception

Exception handling
 Exception can be generated by Java-runtime system or they can be manually generated by code.
          
     Error-Handling becomes a necessary while developing an application to account for exceptional situations that may occur during the program execution, such as
§  Run out of memory
§  Resource allocation Error
§  Inability to find a file
§  Problems in Network connectivity.
If the Resource file is not present in the disk, you can use the Exception handling mechanisim to handle such abrupt termination of program.

§   Exception class: is used for the exceptional conditions that are trapped by the program.
           An exception is an abnormal condition or error that occur during the execution of                                the program.
§   Error: the error class defines the conditions that do not occur under normal conditions.
Eg: Run out of memory, Stack overflow error.

Java.lang.Object                   
  +….Java.Lang.Throwable                                                  Throwable
           +…. Java.lang.Error
   |            +…. A whole bunch of errors
   |                                                                         Exception        Error
  +….Java.Lang.Exception                             (Unchecked, Checked)                                  
         +….Java.Lang.RuntimeException                                             
          |      +…. Various Unchecked Exception
          |
          +…. Various checked Exceptions.

Two types of exceptions:

(1).Checked Exceptions: must be declare in the method declaration or caught in a catch block. 
  Checked exception must be handled at Compile Time. Environmental error that cannot necessarly be detected by Testing, Eg: disk full, brocken Socket, Database unavailable etc.

(2).Un-checked Exceptions: Run-time Exceptions and Error, does’t have to be declare.(but can be caught).
Run-time Exceptions : programming errors that should be detectd in Testing ,
Arithmetic, Null pointer, ArrayIndexOutofBounds, ArrayStore, FilenotFound, NumberFormate, IO, OutofMemory.
ErrorsVirtual mechine error – class not found , out of memory, no such method , illegal access to private field , etc.

Java Exception handling can be managed by five keywords:
§   Try : The try block governs the statements that are enclosed within it and defines the scope of exception handler associated with it.  Try block follows catch or finally or both.

§   Catch: This is a default exception handler. since the exception class is the base class for all the exception class, this handler id capable of catching any type of exception.
    The catch statement takes an Object of exception class as a parameter, if an exception is thrown the statement in the catch block is executed.    The catch block is restricted to the statements in the proceeding try block only.
 Try {
         // statements that may cause exception
       }
catch(Exception obj)
   {

      }
§   Finally : when an exception is raised, the statement in the try block is ignored, some times it is necessary  to process certain statements irrespective of wheather an exception is raised or not, the finally block is used for this purpose.
§   Throw : The throw class is used  to call exception explicitly.  You may want to throw an exception when the user enters a wrong login ID and pass word, you can use throw statement to do so.
The throw statement takes an single argument, which is an Object of exception class.

  Throw<throwable Instance>
If the Object does not belong to a valid exception class the compiler gives error.

§   Throws: The throws statement species the list of exception that has thrown by a method.
         If a method is capable of raising an exception that is does not handle, it must specify the exception has to be handle by the calling method, this is done by using the throw statement.
     [<access specifier>] [<access modifier>] <return type> <method name> <arg-list> [<exception-list>]

Eg: public void accept password( ) throws illegalException
          {
            System.out.println(“Intruder”);
              Throw new illegalAccesException;
           }

Multi Programming

        A multithreaded program contains two or more parts that can run concurrently, Each part a program is called thread and each part that defines a separate path of excution.
 Thus multithreading is a specified from of multitasking .

There are two distinct types of multitasking .
Process:  A Process is , in essence , a program that is executing.
v  Process-based :is  heavy weight- allows you run two or more programs concurrently.
Eg: you can use JAVA compiler at the same time you are using text editor.
  Here a program is a small unit of code that can be dispatched by scheduler .

Thread-based: is Light weight- A Program can perform two or more tasks simultaneously.
Creating a thread:
Eg: A text editor can formate at the same time you can print, as long as these two tasks are being perform separate treads.

Thread: can be defined as single sequential flow of control with in a program.
Single Thread :  Application can perform only one task at a time.
Multithreaded : A process having more than one thread is said to be multithreaded.
  The multiple threads in the process run at the same time, perform different task and interact with each other.
v  Daemon Thread: Is a low priority thread which runs immedeatly on the back ground doing the Garbage Collection operation for the Java Run time System.
SetDaemon( ) – is used to create DaemonThread.

   Creating a Thread:

(1). By implementing the Runnable Interface.
(2). By extending the thread Class.

v  Thread Class: Java.lang.Threadclass is used to construct and access the individual threads in a multithreaded application.

Syntax: Public Class <class name> extends Thread { }
The Thread class define several methods .
o       Getname() – obtain a thread name.
o       Getname() – obtain thread priority.
o       Start( )     - start a thread by calling a Run( ).
o       Run( )       - Entry point for the thread.
o       Sleep( )     - suspend a thread for a period of time.
o       IsAlive( )   - Determine if a thread is still running.
o       Join( )       - wait for a thread to terminate.

v  Runable Interface :   The Runnable interface consist of a Single method Run( ), which is executed when the thread is activated.
    When a  program need ti inherit from another class besides the thread Class, you need to   implement the Runnable interface.
Syntax:   public void <Class-name> extends <SuperClass-name> implements Runnable

Eg: public Class myapplet extends Japplet implements Runnable
      {
         // Implement the Class
      }
* Runnable interface is the most advantageous method to create threads because we need not extend thread Class here.



v  Life Cycle of Thread :

Runnable                      

New Thread  --à                                 ----à  Not Runnable
                                                          ß----

                                 
                                   Dead       The Run( ) terminates .

New Thread: When an instance of a thread class is created, a thread enters the new thread state.        Thread newThread = new Thread(this);
                     You have to invoke the  Start( ) to start the thread.  ie, newThread.Start( );

Runnable: when the Start( ) of the thread is invoked the thread enters into the Runnable State.

Not Runnable: A thread is said to be not runnable state if it
   à Is Slleping
   à Is Waiting
   à Is being blocked by another thread.

               sleep(long t);    where t= no: of milliseconds for which the thread is inactive.
The sleep( ) is a static method because it operates on the current thread.

Dead: A thread can either die natuarally or be killed.
- A thread dies a natural death when the loop in the Run( ) is complete.
- Assigning null to the thread Object kills the thread.
- If th loop in the Run( ) has a hundread iterations , the life of the thread is a hundread iterators of the loop.

IsAlive( ): of the thread class is used to determine wheather a thread has been started or stopped. If isAlive( ) returns true the thread is still running otherwise running completed.

Thread Priorities: are used by the thread scheduler to decide when each thread should ne allowed to run.To set a thread priority, use te setpriority( ), which is a member of a thread.
     final void setpriority(int level)     - here level specifies the new priority seting for the calling thread.

   The value level must be with in the range :-
 MIN_PRIORITY    = 1
 NORM_PRIORITY = 5
 MAX_PRIORITY   = 10

You can obtain the current priority setting by calling getpriority( ) of thread.
   final int getpriority( )



No comments:

Post a Comment