EXCEPTION

Document Sample
EXCEPTION Powered By Docstoc
					EXCEPTION




            1
             3 Types of Errors


Even the most carefully designed program
may still contain errors.
Therefore, the coding process is never
complete until you eliminate all types of
errors.
  Syntax Errors
  Run-Time Errors
  Logic Errors

                                        2
                          Syntax Errors
 Think of a syntax error as a “grammatical” error.
 Such an error is caught by the compiler (“compile-time
 error”).
 Syntax errors are automatically found, usually the
 easiest to fix.
    Most of the time, Java will even underline syntax errors.
 You cannot run code until all syntax errors are fixed.
 Unfortunately, error messages from the compiler may be
 misleading.

Example:
 Misspelling a command, for example rturn instead of
 return

                                                                3
                 Run-Time Errors

 A run-time error is an execution error (occurs
 during run-time).
 Such errors are not always so easy to fix.
 Error messages at run time may or may not
 be helpful.

Example: Divide-by-0
 If your program attempts to divide by zero, it
 automatically terminates and prints an error
 message.
                                                  4
                        Logic Errors
Just because it compiles and runs without getting an
  error message does not mean the code is correct!

 Logic errors indicate an mistake in the design (i.e., the
 algorithm) or its implementation.
    code compiles without errors
    no run-time error messages
    but incorrect action or data occurs during execution
 Generally these errors are the most difficult to find and fix.
 Therefore, you need to be alert and test thoroughly.
    Think about test cases and predict results before
    running the code.


                                                           5
             Logic Error Examples

Algorithm Error:
  averageOfFiveScores = SumOfScores/2;
  (should divide by 5)


Implementation Error:
  typed in wrong symbol in source code
    sum = a - b;
  (should be sum = a + b;)




                                         6
            Exception vs. Error



Exception               Error
  Problem occurs          Problem concerns
  during run-time         the logic and syntax
  A program can           error.
  recover from            A program can not
  exception               recover from an
                          error.




                                                 7
                  Exception Hierarchy



                            Exception




IOException             AWTException                RunTimeException




  ArithmeticException           IllegalArgumentException



                                NumberFormatException




                                                                       8
              Exception Handling Overview
 A way  of organizing a program into sections for the normal
case and the exceptional case
   »exception examples:
   division by zero
   incorrect type of input
 A way of implementing programs incrementally
   »write & debug the code for normal operation first
   »add code for the exceptional case later
 Simplifies development, testing, debugging and maintenance
   »errors are easier to isolate


                                                                9
            Exception Handling


Let Java (Java Virtual Machine – JVM)
handles.
Your program provides the handler:
  Exception handler is in the method where the
  exception occurs.
  Propagate the exception handler in other
  methods.




                                                 10
                             Java Handles the Exception
import java.lang.* ;
import java.io.* ;

    public class Square
    {

     public static void main ( String[] a ) throws IOException
     {
BufferedReader stdin = new BufferedReader ( new InputStreamReader( System.in ) );

            String inData;
            int num ;

            System.out.println("Enter an integer:");
            inData = stdin.readLine();

num = Integer.parseInt( inData );          // convert inData to int

System.out.println(“The square of “ + inData + “ is “ + num*num );

        }
    }


                                                                                    11
What happens if character ‘r’ is an input?


 An object of class NumberFormatException is
 created.
 The object is thrown away from the method and the
 JVM is searching for the handler to handle the thrown
 away object.
 Since the program does not provide any Exception
 Handler to handle the NumberFormatException’s
 object, JVM will handle the object.
 The call stack trace will be printed as an output.




                                                    12
                           Call Stack Trace
Exception in thread “main” java.lang.NumberFormatException: r
     at java.lang.Integer.parseInt(Integer.java:400)
     at java.lang.Integer.parseInt(Integer.java:405)
     at Square.main(Square.java: 16)

a)   java.lang.NumberFormatException: r
        State type of Exception occurs & what causes the Exception.

b)   at java.lang.Integer.parseInt(Integer.java:400)
     at java.lang.Integer.parseInt(Integer.java:405)
     at Square.main(Square.java: 16)

        State in which method and line in that method cause the exception.



                                                                             13
             Some Terminology


Throwing an exception: signal when
something unusual happens
  May be (predefined and) thrown in the Java
  language
  May be thrown in your own code
Catching (or handling) an exception:
responding to an exception with appropriate
code


                                               14
        Exception Handler in the method where it
                        occurs
try
{
      //the code which will cause the exception
}
 catch(SomeExceptionType ex)
{
    //the code which will handle an object of that exception class
}
:://more catch blocks
 catch(AnotherExceptionType ex)
{}
 finally
{//the code which will always executed}
//Statements following the structure

                                                                     15
     Exception Handler in the method where it
                     occurs


• The normal case is handled in a try-block.
• The exceptional case is handled in a
  catch-block.
• The catch-block takes a parameter of type
  Exception.
• If an exception is thrown, execution in the
 try-block ends and control passes to the
 catch-block(s) after the try-block

                                                16
                                       Example
import java.lang.* ;
 import java.io.* ;
    public class Square
    {
      public static void main ( String[] a ) throws IOException
      {
BufferedReader stdin = new BufferedReader ( new InputStreamReader( System.in ) );
        String inData;
        int num ;
        System.out.println("Enter an integer:");
        try
        {
          num = Integer.parseInt(stdin.readLine());
System.out.println("The square of " + inData + " is " + num*num );
        }
        catch (NumberFormatException ex )
        {
          System.out.println("You entered bad data." );
          System.out.println("Run the program again." );
        }
        System.out.println("Good-bye" );        }    }


                                                                                    17
What happens if character ‘r’ is an input?
An object of NumberFormatException is created.
The object is thrown away from the try block and
JVM is searching for the handler (since it is thrown
away from the try block, the JVM will search for the
match catch{} block).
In the program, there is a matched catch{}. So, the
program control will go into the code in the catch{}.
Hence the output:
 You entered bad data.
 Run the program again.
Then the control will go to the next statement
following the last catch{} block, in this case, will
result in the output:
 You entered bad data.
 Run the program again.
 Good-bye
                                                        18
                    How try, catch{} & finally{} works
                                    Pick best match           No
                                                              Match


try                      catch     catch              catch
{                        {         {                  {

}                        }         }                  }          Execution
                                                                 leaves this
                                                                 method
          No Exception




finally
{

}




                                                                      19
  try block




Exception 1?                           catch block 1




Exception 2?                            catch block 1




Exception n?                              catch block 1


                      finally block




     Exception handling control flow

                                                          20
                                         More Examples
import java.lang.* ;
    import java.io.* ;
public class FinallyPractice
    {
      public static void main ( String[] a ) throws IOException
      {
        BufferedReader stdin = new BufferedReader ( new InputStreamReader( System.in ) );
        String inData; int num=0, div=0 ;
         try
        {
          System.out.println("Enter the numerator:");
                num = Integer.parseInt(stdin.readLine() );
          System.out.println("Enter the divisor:");
                div = Integer.parseInt(stdin.readLine() );
          System.out.println( num + " / " + div + " is " + (num/div) );    }
       catch (ArithmeticException ex )
        {         System.out.println("You can't divide " + num + " by " + div);       }
         finally
        {         System.out.println("If the division didn't work, you entered bad data." ); }

      System.out.println("Good-bye" );        }     }



                                                                                                 21
                                        More Examples
import java.io.*;
class TestSum
{public static void main(String[]arg)
            {          double num[] = new double[5]; double jum = 0;

BufferedReader st = new BufferedReader(new InputStreamReader(System.in));
 try
{          System.out.println("Masukkan bilangan nombor:");
           int max = Integer.parseInt(st.readLine());
           for(int i=0; i<max; i++){
                       num[i] = Double.parseDouble(st.readLine());
                       jum+=num[i];}
                       System.out.println("Jumlah: " +jum);
}
 catch(NumberFormatException e)
{          System.out.println("You input a wrong data type");}
 catch(IOException ex)
{                      System.out.println("Problem with the input");}
 catch(IndexOutOfBoundsException e)
{          System.out.println("Index melebihi saiz tatasusunan");}
 finally
{          System.out.println("Good day");}}}


                                                                            22
            Propagate the Exception Handler in different
                             method
public class Pd
{           public void metod1(int i, int j)
            {           System.out.println("metod1 bermula");
                        try
                        {metod2(i,j);
                        }
                        catch(ArithmeticException e)
                        {          System.out.println("i=" +i+ "\tj=" +j);}
                        System.out.println("metod1 berakhir");
            }
            public void metod2(int i, int j) throws ArithmeticException
            {           System.out.println("metod2 bermula");
                        j = i/j;
                        System.out.println("metod2 berakhir");
                        metod3(i,j);}
            public void metod3(int i, int j) throws ArithmeticException
            {           System.out.println("metod3 bermula");
                        j=i/j;
                        System.out.println("metod3 berakhir");}
            public static void main (String[] a)
            {           Pd p = new Pd();
                        p.metod1(1,1); // tiada exception yang berlaku
                        p.metod1(1,0); // exception berlaku di metod2
                        p.metod1(0,1); // exception berlaku di metod3}}       23
How it works




               24
                   Throw Statement


The throw exception object can be used if the
exception is subject to a condition (as in the
following example).
Rule:
  For every method which throw an exception object, a throws
  clause must be included in the method header:
    public static int calcInsurance(String birth) throws Exception




                                                                     25
                                       Example
import java.io.*;
class TestDivide
{public static void main(String[]arg) throws IOException, ArithmeticException
{
BufferedReader st = new BufferedReader(new InputStreamReader(System.in));
 try
{
      int denom = Integer.parseInt(st.readLine());
      if(denom<=0)
                  throw new ArithmeticException("Input positive denom");
      System.out.println("Value of 100/denom:" +100/denom);
}

catch(ArithmeticException ex)
{
     System.out.println("Arithmetic Exception occurs!");
}

catch(NumberFormatException ex)
{
     System.out.println("Wrong data type!!");
}
}
}
                                                                                26
                Exception Object


Has many method which we can call in the program,
for example:
   public void printStackTrace() : will print the stack
   trace.
   public String getMessage(): will return a message
   string which will explain about the exception
   occurs.




                                                      27
                                              Example
import java.lang.* ;
 import java.io.* ;
  public class IndexPractice
     {
       public static void main ( String[] a ) throws IOException
       {
         BufferedReader stdin = new BufferedReader ( new InputStreamReader( System.in ) );
         String inData; int data=0, slot=0 ;
         int[] value = new int[10];
         try
         { System.out.println("Enter the data:");
              data = Integer.parseInt(stdin.readLine);
           System.out.println("Enter the array index:");
              slot = Integer.parseInt(stdin.readLine() );
            value[slot] = data;       }
          catch (NumberFormatException ex )
         { System.out.println("This is your problem: " + ex.getMessage()
              + "\nHere is where it happened:\n");
           ex.printStackTrace();        }
          catch (IndexOutOfBoundsException ex )
         {
   System.out.println("This is your problem: " + ex.getMessage() + "\nHere is where it happened:\n");
           ex.printStackTrace();        }
          System.out.println("Good-by" );        }    }
                                                                                                 28
         Creating your own Exception class
Steps:
a) Define the Exception class as a subclass to the
    Exception class:
        public class MyException extends Exception
b)   Build a constructor
     public MyException(int i)
     {
     value = i;
     }
c) Override a super class method
     public String getMessage()
     {
       return message;
     }
d) Steps a)+ b) + c)
                                                     29
  Overall Picture



 Exception




MyException




                    30
public class MyException extends Exception {

 private int value;
 private String message;

  public MyException(int i) {
    value = i;
    message = new String("MyException occurs at value: " +
value);
  }
 public String getMessage() {
    return message;
  }
}
                                                             31
                    How to use the user-defined exceptions?

public class Propagate {
 public void method1(int i) {
   try {
     method2(i);
   }
   catch(MyException e) {
     System.out.println(e.getMessage());
   } }
  public void method2(int i) throws MyException {
   if(i == 1)
     throw new MyException(i);
   else {
     method3(i);
   } }
  public void method3(int i) throws MyException {
   if(i == 0)
     throw new MyException(i);
   else
     System.out.println("i = " + i);
 }
  public static void main(String[] args) {
   Propagate p = new Propagate();
   for (int i = 0; i < 3; i++)
     p.method1(i); }}
                                                              32

				
DOCUMENT INFO