Packages , Interfaces and
Exception Handling
          Dr. Kiran K. Tangod
          Professor & Head
      Department of ISE, KLS, GIT
Packages
• Java provides a mechanism for partitioning the class name space into
  more manageable chunks. This mechanism is the package.
• The package is both a naming and a visibility control mechanism.
• By defining classes inside a package that are not accessible by code
  outside that package.
• class members can be defined such that they are only exposed to
  other members of the same package.
• This allows your classes to have intimate knowledge of each other,
  but not expose that knowledge to the rest of the world
Defining a Package
• Package can be created by including a package command as the first
  statement in a Java source file. Any classes declared within that file
  will belong to the specified package.
• The package statement defines a name space in which classes are
  stored. If you omit the package statement, the class names are put
  into the default package, which has no name.
• For real applications. Most of the time, it is recommended to define a
  package.
• This is the general form of the package statement:
                               package pkg;
Packages:
• Java uses file system directories to store packages.
• For example, the .class files for any classes you declare to be part of
  MyPackage must be stored in a directory called MyPackage.
• Remember that case is significant, and the directory name must
  match the package name exactly.
Multileveled package statement
• Hierarchy of packages can also be created in Java.
• The general form of a multileveled package statement :
                      package pkg1[.pkg2[.pkg3]];
• A package hierarchy must be reflected in the file system of your Java
  development system.
• For example, a package declared as package java.awt.image; needs to
  be stored in java\awt\image in a Windows environment
A Short Package Example
Access Protection
• Java addresses four categories of visibility for class members:
    • Subclasses in the same package
    • Non-subclasses in the same package
    • Subclasses in different packages
    • Classes that are neither in the same package nor subclasses
• The three access specifiers, private, public, and protected,
  provide a variety of ways to produce the many levels of
  access required by these categories.
Class member access
Importing Packages
• Java includes the import statement to bring certain classes, or entire
  packages, into visibility
• The import statement is a convenience to the programmer and is not
  technically needed to write a complete Java program.
• Import statement helps in code reusability
• General form:
                      import pkg1[.pkg2].(classname|*);
Here, pkg1 is the name of a top-level package, and pkg2 is the name of a
subordinate package inside the outer package separated by a dot (.).
Example:
import java.util.Date; //explicit class name Date
import java.io.*;        // import the entire package
Interfaces
• Using the keyword interface, you can fully abstract a class’ interface
  from its implementation.
• Interface specifies what a class must do, but not how it does it.
• Interfaces are syntactically similar to classes, but they lack instance
  variables.
• Methods in interface are declared without any body.
• Implementation details of methods are not included in interface.
• Once interface is defined, any number of classes can implement an
  interface
Defining an Interface
  access interface name {
     return-type method-name1(parameter-list);
     return-type method-name2(parameter-list);
     type final-varname1 = value;
     type final-varname2 = value;
     // ...
     return-type method-nameN(parameter-list);
     type final-varnameN = value;
  }
 Implementation of interface
 Example:
 interface Callback {
 void callback(int param);
 }
class classname [extends superclass] [implements interface[,interface...]] {
// class-body
}
 Example
Exception-Handling Fundamentals
• A Java exception is an object that describes an exceptional (that is, error)
  condition that has occurred in a piece of code.
• When an exceptional condition arises, an object representing that
  exception is created and thrown in the method that caused the error.
• That method may choose to handle the exception itself, or pass it on.
• Exceptions can be generated by the Java run-time system, or they can be
  manually generated by your code.
• Exceptions thrown by Java relate to fundamental errors that violate the
  rules of the Java language or the constraints of the Java execution
  environment.
• Manually generated exceptions are typically used to report some error
  condition to the caller of a method.
• Java exception handling is managed via five keywords: try, catch, throw,
  throws, and finally.
Exception-Handling Fundamentals
• Program statements that you want to monitor for exceptions are
  contained within a try block. If an exception occurs within the try
  block, it is thrown.
• Program code can catch this exception (using catch) and handle it.
• System-generated exceptions are automatically thrown by the Java
  run-time system.
• Keyword throw is used to manually throw an exception.
• Every time a method generates an exception, it must be explicitly
  declared using a 'throws' clause.
• Code that must be executed madatorilly after the completion of a try
  block is placed within a finally block.
General form of an exception-handling block:
 try {
         // block of code to monitor for errors
 }catch (ExceptionType1 exOb) {
            // exception handler for ExceptionType1
  }
  catch (ExceptionType2 exOb) {
            // exception handler for ExceptionType2
  }
  // ...
  finally {
            // block of code to be executed after try
  block ends
  }                      Here, ExceptionType is the type of exception that has occurred.
Exception Types
Exception Types
• All exception types are subclasses of the built-in class Throwable.
• Throwable is at the top of the exception class hierarchy.
• Immediately below Throwable are two subclasses that partition exceptions
  into two distinct branches. One branch is headed by Exception and another
  is Error.
• This class is used for exceptional conditions that user programs should
  catch.
• This is also the class that you will subclass to create your own custom
  exception types.
• There is an important subclass of Exception, called RuntimeException.
• RuntimeException are automatically defined for the programs that you
  write and include things such as division by zero and invalid array indexing.
Java Exception hierarchy
Uncaught Exceptions
class Exc0 {
public static void main(String args[]) {
   int d = 0;
   int a = 42 / d;
   }
}
java.lang.ArithmeticException: / by zero
at Exc0.main(Exc0.java:4)
Using try and catch
• To guard against and handle a run-time error, simply enclose the code
  that you want to monitor inside a try block.
• Immediately following the try block, include a catch clause that
  specifies the exception type that is to be caught.
 class Exc2 {
 public static void main(String args[]) {
        int d, a;
        try { // monitor a block of code.
        d = 0;
        a = 42 / d;
        System.out.println("This will not be printed.");
     } catch (ArithmeticException e) { // catch divide-by-zero error
              System.out.println("Division by zero.");
   }
   System.out.println("After catch statement.");                       Output:
   }                                                                   Division by zero.
 }                                                                     After catch statement.
Using try and catch
• println( ) inside the try block is never executed.
• Once an exception is thrown, program control transfers out of the try
  block into the catch block. Put differently, catch is not “called,” so
  execution never “returns” to the try block from a catch.
• The line “This will not be printed.” is not displayed.
• Once the catch statement has executed, program control continues
  with the next line in the program following the entire try/catch
  mechanism.
Displaying a Description of an Exception
catch (ArithmeticException e) {
System.out.println("Exception: " + e);
a = 0; // set a to zero and continue
}
When this is written in the program, and the program is run, each
divide-by zero error displays the following message:
Exception: java.lang.ArithmeticException: / by zero
Multiple catch Clauses
• More than one exception could be raised by a single piece of code.
• In such situations, it is possible to specify two or more catch clauses,
  each catching a different type of exception.
• When an exception is thrown, each catch statement is inspected in
  order, and the first one whose type matches that of the exception is
  executed.
• After one catch statement executes, the others are bypassed, and
  execution continues after the try/catch block.
    Demonstrate multiple catch statements
class MultiCatch {                          catch(ArithmeticException e) {
public static void main(String args[]) {    System.out.println("Divide by 0: " + e);
try {                                       }
int a = 0; //causes / by zero               catch(ArrayIndexOutOfBoundsExceptio
                                            n e) {
//if a!=0 causes array index out of bound   System.out.println("Array index oob: " +
System.out.println("a = " + a);             e);
int b = 42 / a;                             }
int c[] = { 1 };                            System.out.println("After try/catch
c[42] = 99; //array index out of bound      blocks.");
}                                           }
                                            }
Nested try Statements, throw, throws, finally.
• The try statement can be nested. That is, a try statement can be inside the
  block of another try.
• Each time a try statement is entered, the context of that exception is
  pushed on the stack.
• If an inner try statement does not have a catch handler for a particular
  exception, the stack is unwound and the next try statement’s catch
  handlers are inspected for a match.
• This continues until one of the catch statements succeeds, or until all of the
  nested try statements are exhausted.
• If no catch statement matches, then the Java run-time system will handle
  the exception.
Nested try Statements, throw, throws, finally.
class NestTry {                     if(a==2) {
public static void main(String      int c[] = { 1 };
args[]) {                           212 Part I: The Java Language
try {                               c[42] = 99; // generate an out-of-bounds
                                    exception
int a = args.length;
                                    }
int b = 42 / a;
                                    } catch(ArrayIndexOutOfBoundsException e) {
System.out.println("a = " + a);     System.out.println("Array index out-of-bounds:
try { // nested try block           " + e);
if(a==1) a = a/(a-a); // division   }
by zero                             } catch(ArithmeticException e) {
                                    System.out.println("Divide by 0: " + e);
                                    }
                                    }
                                    }