Java Exception Handling Guide
Java Exception Handling Guide
Errors
7) Types of errors :
   1. Syntax error
   2. Logical error
   3. Runtime error
   4. Compile time error
 1. Syntax error– These types of error occurred due to incorrect grammar in the
    programming language. Syntax error is found during the execution of the program.
     1)   Error in structure
     2)   Missing operators
     3)   Unbalanced parenthesis, square brackets and curly braces
     4)   Missing semicolons
     5)   Misspelled variable and function names
     6)   Incorrect format in semicolon and loop statements.
 2. Logical error –These errors are due to the mistakes made by the programmer. It will
     not be detected by a compiler nor by the JVM. Errors may be due to wrong idea or
     concept used by a programmer while coding.
                                                                      Prof. R. S. Patil   1
4th Semester-JPR[22412]                     Chapter-4         Exception Handling and Multithreading
 3. Runtime error – Runtime errors occur during the execution of program. These errors
     are errors which occur when the program is running. Run time errors are not detected
     by the java compiler. It is the JVM which detects it while the program is running.
 4. Compile time error - Semantic errors are compile time errors. The compiler will list
     the line number and even the word that is causing the issue. These types of error are
     detected at compile time. Most of the compile time errors are scope and declaration
     error.
                   Error                                         Exception
 1. Impossible to recover from an error.   1. Possible to recover from exceptions.
 2. Errors are of type ‘unchecked’.        2. Exceptions can be either ‘checked’ or ‘unchecked’.
 3. Occur at runtime.                      3. Can occur at compile time or run time.
 4. Caused by the application running
                                           4. Caused by the application itself.
environment.
5.They are defined in java.lang.Error      5.They are defined in java.lang.Exception package
package.
                                           6.Examples :
6.Examples :                               Checked Exceptions : SQLException, IOException
java.lang.StackOverflowError,              Unchecked Exceptions :
java.lang.OutOfMemoryError                 ArrayIndexOutOfBoundException,
                                           NullPointerException, ArithmeticException.
                                                                          Prof. R. S. Patil   2
4th Semester-JPR[22412]                   Chapter-4         Exception Handling and Multithreading
       statement 1;
       statement 2;
       statement 3; //exception occurs
       statement 4;
       statement 5;
   7. If we perform exception handling, the rest of the statement will be executed. That is
      why we use exception handling in Java.
                                                                       Prof. R. S. Patil   3
4th Semester-JPR[22412]                Chapter-4        Exception Handling and Multithreading
1) Checked Exception :-
   1. The classes which directly inherit Throwable class except RuntimeException and
      Error are known as checked exceptions. e.g. IOException, SQLException etc.
   2. Checked exceptions are checked at compile-time.
   3. If some code within a method throws a checked exception, then the method must
      either handle the exception or it must specify the exception using throws keyword.
   4. At run time, these exceptions may occur or not but it is responsibility of
      programmer to compulsory handle these exceptions in the program by writing
      exception handling code.
   5. Example –IOException, SQLException, ClassNotFoundException, InterruptException
      etc.
                                                                   Prof. R. S. Patil   4
4th Semester-JPR[22412]                  Chapter-4        Exception Handling and Multithreading
2) Unchecked Exception :-
3) Error :-
   1. try
   2. catch
   3. finally
   4. throw
   5. throws
                                                                     Prof. R. S. Patil   5
4th Semester-JPR[22412]                     Chapter-4         Exception Handling and Multithreading
1. try
      1. A keyword “try” is used for block of code that causes an error condition and
         “throws” an exception.
      2. The try block contains a set of statements where an exception can occur.
      3. It is always followed by a catch block, which handles the exception that occurs in the
         associated try block.
      4. Java try block must be followed by either catch blocks or finally block or both.
2. catch
      1. A keyword “catch” is used for block of code that “catches” the exception
         thrown by the “try” block and handles it properly.
      2. This block is also known as Exception Handler.
      3. A catch block is where you handle the exceptions and this catch block must be used
         after the try block.
      4. A single try block can have multiple catch blocks associated with it. You can catch
         different exceptions in different catch blocks.
Syntax :-
try
  {
      Statement ; //generates an exception
    }
 catch(Exception-type e)
 {
      Statement ; //processes the exception
  }
Example-1-
      class Test
     {
        public static void main(String args[ ])
         {
           int a = 100 , b = 0, c ;
           c = a / b;
           System.out.println( c );
         }
       }
                                                                         Prof. R. S. Patil   6
4th Semester-JPR[22412]                             Chapter-4   Exception Handling and Multithreading
       Output-
             Exception in thread "main" java.lang.ArithmeticException: / by zero
            At Test.main(Test.java 6)
Above program is not executed. There can be 100 lines of code after exception. So all the
code after exception will not be executed.
Let's see the solution of the above problem by a java try-catch block.
Example-2-
       class Test
         {
           public static void main(String args[ ])
            {
               try
                 {
                        int a = 100 , b = 0 , c ;
                        c = a / b;
                        System.out.println( c );
                    }
               catch(ArithmeticException e)
                 {
                   System.out.println(e);
                 }
       Output-
                          java.lang.ArithmeticException: / by zero
                          Hello
Now, as displayed in the above example, the code after catch is executed, i.e., the Hello
statement is printed.
                                                                           Prof. R. S. Patil   7
4th Semester-JPR[22412]                        Chapter-4             Exception Handling and Multithreading
Examples:-
5. At a time only one exception occurs and at a time only one catch block is executed.
Example-1-
       class MultipleCatchEx
       {
          public static void main(String args[ ])
           {
             try
              {
                 int a[ ] = new int[5];
                 a [5] = 30/0;
               }
                catch(ArithmeticException e)
                {
                  System.out.println("Arithmetic Exception occurs");
                }
              catch(ArrayIndexOutOfBoundsException e)
               {
                System.out.println("ArrayIndexOutOfBounds Exception occurs");
               }
             catch(Exception e)
              {
               System.out.println("Parent Exception occurs");
               }
            System.out.println("rest of the code");
         }
       }
        Output-
                    Arithmetic Exception occurs
                    rest of the code
3. finally :-
   1) Java finally block is a block that is used to execute important code or to put
      “cleanup” code such as closing connection, stream etc.
   2) Java finally block is always executed whether exception is handled or not.
   3) Java finally block follows try or catch block.
   4) It is written immediately after the try block or after the last catch block.
                                                                       Prof. R. S. Patil   9
4th Semester-JPR[22412]                    Chapter-4       Exception Handling and Multithreading
try
   { ……..
   }
catch(Exception-type e)
  { ……..
   }
finally
 {
     …………… // optional
  }
Example-1-
       class Test
         {
           public static void main(String args[ ])
            {
              try
                {
                   int a = 100, b = 2, c ;
                   c = a / b;
                   System.out.println( c );
                 }
               catch(ArithmeticException e)
                 {
                   System.out.println( e );
                 }
               finally
                 {
                    System.out.println(" I am in finally block");
                  }
               }
           }
       Output -      50
                     I am in finally block
But if we put b = 0 then Exception occur in the program then catch block handle the
exception and we will get the following output
                    java.lang.ArithmeticException / by zero
                           I am in finally block
                                                                      Prof. R. S. Patil   10
4th Semester-JPR[22412]                 Chapter-4        Exception Handling and Multithreading
4.throw keyword:-
Syntax :
In this example, we have created the validate method that takes integer value as a
parameter. If the age is less than 18, we are throwing the ArithmeticException otherwise
print a message welcome to vote.
Example-1-
       Output-
                 Exception in thread main java.lang.ArithmeticException: not valid
5. throws keyword:-
                                                                    Prof. R. S. Patil   11
4th Semester-JPR[22412]                   Chapter-4         Exception Handling and Multithreading
Syntax :
Example-1-
       class Test
       {
          static void check( ) throws ArithmeticException
          {
             System.out.println("Inside check function");
             throw new ArithmeticException(" demo ");
           }
        public static void main(String args[ ])
        {
           try
           {
              check( );
            }
         catch(ArithmeticException e)
          {
              System.out.println("caught : " + e);
           }
       }
    }
Output-
              Inside check function
              caught : java.lang.ArithmeticException: demo
                                                                       Prof. R. S. Patil   12
4th Semester-JPR[22412]                     Chapter-4           Exception Handling and Multithreading
Built-in Exceptions:-
   1) Inside the standard package java.lang, Java defines several exception classes.
   2) The most general built-in exceptions are subclasses of the standard type
      RuntimeException.
   3) Since java.lang is implicitly imported into all Java programs, most exceptions
      derived from RuntimeException are automatically available.
                                                                           Prof. R. S. Patil   13
4th Semester-JPR[22412]                  Chapter-4         Exception Handling and Multithreading
Chained Exceptions:-
   1) Chained exception feature allow you to relate one exception with another exception,
      i.e one exception describes cause of another exception.
   2) For example, consider a situation in which a method throws an
      ArithmeticException because of an attempt to divide by zero but the actual cause of
      exception was an I/O error which caused the divisor to be zero.
   3) The method will throw only ArithmeticException to the caller. So the caller would
      not come to know about the actual cause of exception. Chained Exception is used in
      such type of situations.
   4) Two new constructors and two new methods were added to Throwable class to
      support chained exception.
In the first form, the paramter cause specifies the actual cause of exception. In the second
form, it allows us to add an exception description in string form with the actual cause of
exception.
getCause( ) and initCause( ) are the two methods added to Throwable class.
Example-1-
       import java.io.IOException;
       public class ChainedException
        {
         public static void divide(int a, int b)
         {
           if(b == 0)
            {
             ArithmeticException ae = new ArithmeticException("top layer");
             ae.initCause( new IOException("cause") );
             throw ae;
            }
          else
          {
           System.out.println(a/b);
                                                                      Prof. R. S. Patil   14
4th Semester-JPR[22412]                  Chapter-4         Exception Handling and Multithreading
            }
        }
Example-1-
              System.out.println("welcome to vote");
              }
         public static void main(String args[ ])
           {
              try
              {
              validate(13);
                }
             catch(Exception m)
              {
              System.out.println("Exception occured: " + m);
               }
             System.out.println("rest of the code...");
           }
         }
       Output-
                    Exception occurred: InvalidAgeException: not valid
                    rest of the code…
Multithreading Programming :-
Advantages of Multithreading :-
   1) It doesn't block the user because threads are independent and you can perform
      multiple operations at the same time.
   2) You can perform many operations together, so it saves time.
   3) Threads are independent, so it doesn't affect other threads if an exception occurs in
      a single thread.
                                                                      Prof. R. S. Patil   16
4th Semester-JPR[22412]                  Chapter-4         Exception Handling and Multithreading
Multitasking :-
                                                                      Prof. R. S. Patil   17
4th Semester-JPR[22412]                 Chapter-4        Exception Handling and Multithreading
   6) For example: Typing in Excel, Listening music, drawing diagram in paint and
      downloading file from internet at the same time. Here in example we can clearly see
      that all applications are independent.
Multiprocessing
                                                                    Prof. R. S. Patil   18
4th Semester-JPR[22412]                    Chapter-4         Exception Handling and Multithreading
Thread :-
Threads are independent. If there occurs exception in one thread, it doesn't affect other
threads. It uses a shared memory area.
As shown in the above figure, a thread is executed inside the process. There is context-
switching between the threads. There can be multiple processes inside the OS, and one
process can have multiple threads.
A thread can be in one of the five states. The life cycle of the thread in java is controlled by
JVM. The java thread states are as follows:
   1.   New
   2.   Runnable
   3.   Running
   4.   Non-Runnable (Blocked)
   5.   Terminated (Dead)
                                                                        Prof. R. S. Patil   19
4th Semester-JPR[22412]                      Chapter-4          Exception Handling and Multithreading
New thread
killed thread
Idle thread
   1. New :-
               •    A thread begins its life cycle in the new state. It remains in this state until
                    the program start( ) the thread. It is also referred to as born thread.
   2. Runnable :-
           • After invocation of start( ) method on new thread, the thread becomes
              runnable.
   3. Running :-
           • A thread is in running state if the thread scheduler has selected it.
   5. Terminated/Dead :-
           • A thread enter the terminated state(or dead state) when it complete its
              task. Or its run( ) method exits.
                                                                           Prof. R. S. Patil   20
4th Semester-JPR[22412]                    Chapter-4        Exception Handling and Multithreading
Thread Class :-
      Thread class provide constructors and methods to create and perform operations on
       a thread.
      Thread class extends Object class and implements Runnable interface.
               •   Thread( )
               •   Thread(String name)
               •   Thread(Runnable r)
               •   Thread(Runnable r, String name)
                                                                       Prof. R. S. Patil   21
4th Semester-JPR[22412]                     Chapter-4       Exception Handling and Multithreading
   •   The easiest way to create a thread is to create a class that implements the Runnable
       interface.
   •   To implement Runnable interface, a class need only implement a single method
       called run( ), which is declared like this:
Example-1-
If you are not extending the Thread class, your class object would not be treated as a thread
object. So you need to explicitly create Thread class object. We are passing the object of
your class that implements Runnable so that your class run( ) method may execute.
                                                                       Prof. R. S. Patil   22
4th Semester-JPR[22412]                           Chapter-4   Exception Handling and Multithreading
Example-2-
         x2 b = new x2( );
        Thread t2 = new T hread( b );
        t2.start( );
    }
}
Output-
                     Thread 1….
                     Thread 2….
                     Thread 1….
                     Thread 1….
                     Thread 1….
                     Thread 1….
                     Thread 2….
                     Thread 2….
                     Thread 2….
                     Thread 2….
        •   The second way to create a thread is to create a new class that extends Thread, then
            override the run( ) method and then to create an instance of that class. The run( )
            method is what is executed by the thread after you call start( ).
Example-1-
Example-2-
       Output-
                 Thread main….
                 Thread main….
                 Thread main….
                 Thread main….
                 Thread main….
                 Thread 1….
                 Thread 2….
                 Thread 1….
                 Thread 1….
                 Thread 1….
                 Thread 1….
                 Thread 2….
                 Thread 2….
                 Thread 2….
                 Thread 2….
                 Thread 2….
   •   Each thread have a priority. Priorities are represented by a number between 1 and
       10.
   •   In most cases, thread scheduler schedules the threads according to their priority
       (known as preemptive scheduling).
   •   But it is not guaranteed because it depends on JVM specification that which
       scheduling it chooses.
                                                                   Prof. R. S. Patil   26
4th Semester-JPR[22412]                           Chapter-4        Exception Handling and Multithreading
Example-1-
        m1.setPriority(Thread.MIN_PRIORITY);
        m2.setPriority(Thread.MAX_PRIORITY);
        m1.start( );
        m2.start( );
    }
}
        Output- running      thread   name is : Thread-0
                running      thread   priority is : 10
                running      thread   name is : Thread-1
                running      thread   priority is : 1
Synchronization :-
            1) Synchronization in java is the capability to control the access of multiple threads to
               any shared resource.
            2) Java Synchronization is better option where we want to allow only one thread to
               access the shared resource.
                                                                              Prof. R. S. Patil   27
4th Semester-JPR[22412]                  Chapter-4     Exception Handling and Multithreading
Types of Synchronization :-
   1. Process Synchronization
   2. Thread Synchronization
        class Table
        {
          void printTable(int n) //method not synchronized
           {
             for(int i=1; i<=5; i++)
              {
                System.out.println(n * i);
                try
                {
                 Thread.sleep(400);
                 }
                 catch(Exception e)
                {
                   System.out.println(e);}
                 }
             }
          }
                                                                  Prof. R. S. Patil   28
4th Semester-JPR[22412]                  Chapter-4           Exception Handling and Multithreading
       MyThread2(Table t)
           {
              this.t = t;
            }
         public void run( )
         {
         t.printTable(100);
         }
       }
       class SynchroEx
        {
          public static void main(String args[ ])
            {
               Table obj = new Table( ); //only one object
               MyThread1 t1 = new MyThread1(obj);
               MyThread2 t2 = new MyThread2(obj);
               t1.start( );
               t2.start( );
             }
          }
       Output-
                     5
                     100
                     10
                     200
                     15
                     300
                     20
                     400
                     25
                     500
                                                                        Prof. R. S. Patil   29
4th Semester-JPR[22412]              Chapter-4       Exception Handling and Multithreading
Example-1-
       class Table
        {
          synchronized void printTable(int n) // synchronized method
           {
             for(int i=1; i<=5; i++)
              {
                System.out.println(n * i);
                try
                {
                 Thread.sleep(400);
                 }
                 catch(Exception e)
                {
                   System.out.println(e);}
                 }
             }
          }
                                                                Prof. R. S. Patil   30
4th Semester-JPR[22412]                  Chapter-4           Exception Handling and Multithreading
       class SynchroEx
        {
          public static void main(String args[ ])
            {
               Table obj = new Table( ); //only one object
               MyThread1 t1 = new MyThread1(obj);
               MyThread2 t2 = new MyThread2(obj);
               t1.start( );
               t2.start( );
             }
          }
Output-
                   5
                   10
                   15
                   20
                   25
                   100
                   200
                   300
                   400
                   500
 1. In multithreading sometimes output generated by one thread acts as input for another
    thread. And when the output is used by second thread, the first thread has to generate
    another output.
 2. Here the question is ; how second thread will come to know that the first thread has
    created new output and also how first thread will know that the output generated by it
    is used by second thread.
 3. For this purpose in initial days, concept of polling was used in which a continues loop
    was running to check the values. But this waste many CPU cycles and makes the
    implementation inefficient. Hence java gives the solution of inter-thread
    communication.
 4. To avoid polling, Java uses three methods, namely, wait( ), notify( ) and notify( ).
Example-1-
                                                                        Prof. R. S. Patil   31
4th Semester-JPR[22412]                      Chapter-4         Exception Handling and Multithreading
class Customer
{
    int amount = 10000;
    synchronized void withdraw(int amount)
     {
        System.out.println("going to withdraw...");
       if(this.amount < amount)
         {
           System.out.println("Less balance; waiting for deposit...");
           try
            {
               wait( );
             }
           catch(Exception e)
            {
              }
        }
     this.amount - = amount;
     System.out.println("withdraw completed...");
  }
  class Test
   {
     public static void main(String args[ ])
      {
        final Customer c = new Customer( );
        new Thread( )
         {
           public void run( )
           {
             c.withdraw(15000);
           }
                                                                          Prof. R. S. Patil   32
4th Semester-JPR[22412]                     Chapter-4        Exception Handling and Multithreading
}.start( );
         new Thread( )
         {
           public void run( )
            {
               c.deposit(10000);
             }
         }.start( );
     }
}
    Output-
               going to withdraw...
               Less balance; waiting for deposit...
               going to deposit...
               deposit completed...
               withdraw completed
Deadlock in java:-
Prof. R. S. Patil 33