Object Oriented Programming with JAVA (BCS306A)
MODULE -4
Packages: Packages, Packages and Member Access, Importing Packages.
Exceptions: Exception-Handling Fundamentals, Exception Types, Uncaught
Exceptions, Using try and catch, Multiple catch Clauses, Nested try Statements, throw,
throws, finally, Java’s Built-in Exceptions, Creating Your Own Exception Subclasses, Chained
Exceptions.
Chapter 9, 10
Defining a Package
• Packages are containers for a set of classes and interfaces.
• To create a package, include 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.
• While the default package is fine for short, sample programs, it is inadequate for real
applications.
• Syntax of package statement:
package package-name;
Example,
package mypackage;
• 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 : the directory name must match the package name exactly.
• The package statement simply specifies to which package the classes defined in a file
belong.
Prepared By : Linda R, Asst Professor in CSE, Dr. TTIT, KGF 1
Object Oriented Programming with JAVA (BCS306A)
Example:
OUTPUT:
Anthony: $-12.33 Packages and Member Access
Prepared By : Linda R, Asst Professor in CSE, Dr. TTIT, KGF 2
Object Oriented Programming with JAVA (BCS306A)
• Java provides many levels of protection to allow control over the visibility of variables
and methods within classes, subclasses, and packages.
• Java addresses four categories of visibility for class members:
Same package subclasses
Same package non-subclasses
Different package subclasses
Different package non-subclasses
The three access modifiers, private, public, and protected, provide a variety of ways to
produce the many levels of access required by these categories. Table below sums up the
interactions.
We can simplify it as follows.
• Anything declared public can be accessed from different classes and different packages.
• Anything declared private cannot be seen outside of its class.
• Anything default is visible to subclasses as well as to other classes in the same package.
• Anything declared protected will be seen outside current package, but only to classes
that subclass your class directly.
Prepared By : Linda R, Asst Professor in CSE, Dr. TTIT, KGF 3
Object Oriented Programming with JAVA (BCS306A)
//This is file [Link]: package
p1;
public class Protection
{
int n = 1; private int
n_pri = 2; protected int
n_pro = 3; public int n_pub =
4;
Protection()
{
[Link]("base constructor");
[Link]("n = " + n);
[Link]("n_pri = " + n_pri);
[Link]("n_pro = " + n_pro);
[Link]("n_pub = " + n_pub);
}
}
//This is file [Link]:
package p1;
class Derived extends Protection
{
Derived()
{
[Link]("derived constructor");
[Link]("n = " + n);
// [Link]("n_pri = " + n_pri); class only access
[Link]("n_pro = " + n_pro);
[Link]("n_pub = " + n_pub);
}
}
Prepared By : Linda R, Asst Professor in CSE, Dr. TTIT, KGF 4
Object Oriented Programming with JAVA (BCS306A)
//This is file [Link]: package
p1;
class SamePackage
{
SamePackage()
{
Protection p = new Protection();
[Link]("same package constructor");
[Link]("n = " + p.n);
// [Link]("n_pri = " + p.n_pri); class only access
[Link]("n_pro = " + p.n_pro);
[Link]("n_pub = " + p.n_pub);
}
}
package p2;
class Protection2 extends [Link]
{
Protection2()
{
[Link]("derived other package constructor");
// [Link]("n = " + n); class or package only access
// [Link]("n_pri = " + n_pri); class only access
[Link]("n_pro = " + n_pro);
[Link]("n_pub = " + n_pub);
}
}
//This is file [Link]:
package p2;
class OtherPackage
{
OtherPackage()
{
[Link] p = new [Link]();
Prepared By : Linda R, Asst Professor in CSE, Dr. TTIT, KGF 5
Object Oriented Programming with JAVA (BCS306A)
[Link]("other package constructor");
// [Link]("n = " + p.n); class or package only access
// [Link]("n_pri = " + p.n_pri); class only access
// [Link]("n_pro = " + p.n_pro);
[Link]("n_pub = " + p.n_pub);
}}
If you want to try these two packages, here are two test files you can use. The
one for package p1 is shown here:
// Demo package p1. import p1.*;
public class Demo base classconstructor
n=1 n_pri = 2 n_pro = 3
{
n_pub = 4
public static void main(String[] args)
derived constructor
{ n= 1 n_pro
Protection ob1 = new Protection(); = 3 n_pub
=4
Derived ob2 = new Derived();
same package
SamePackage ob3 = new SamePackage();
constructor
}
n= 1 n_pro
} = 3 n_pub
=4
// Demo package p2.
import p2.*
public class Demo
{
public static void main(String[] args)
{
Protection2 ob1 = new Protection2();
OtherPackage ob2 = new OtherPackage();
}
}
Importing Packages.
• Java includes the import statement to bring certain classes, or entire packages, into
visibility.
• Once imported, a class can be referred to directly, using only its name.
Prepared By : Linda R, Asst Professor in CSE, Dr. TTIT, KGF 6
Object Oriented Programming with JAVA (BCS306A)
• The import statement is a convenience to the programmer and is not technically needed
to write a complete Java program.
• If you are going to refer to a few dozen classes in your application, however, the import
statement will save a lot of typing.
• In a Java source file, import statements occur immediately following the package
statement (if it exists) and before any class definitions.
• General syntax of the import statement:
import pkg1 [.pkg2].(classname | *);
Example:
import [Link];
import [Link].*;
• The basic language functions are stored in a package called [Link].
• [Link] package is imported implicitly for all program as follows:
import [Link].*;
• The import statement is optional.
• For example, this fragment uses an import statement:
import [Link].*; class MyDate extends Date
// with import
{
….
}
The same example without the import statement looks like this:
class MyDate extends [Link] // without import
{
….
}
Example:
• When a package is imported, only those items within the package declared as public will
be available to non-subclasses in the importing code.
Prepared By : Linda R, Asst Professor in CSE, Dr. TTIT, KGF 7
Object Oriented Programming with JAVA (BCS306A)
• For example, if you want the Balance class of the package mypack shown earlier to be
available as a stand-alone class for general use outside of mypack, then you will need to
declare it as public and put it into its own file, as shown here:
/*The Balance class, its constructor, and its show() method are public. This means that they
can be used by non-subclass code outside their package. */
package mypack;
public class Balance
{
String name;
double bal;
public Balance(String n, double b)
{
name = n;
bal = b;
}
public void show()
{ if(bal<0)
{
[Link](name + ": $" + bal);
}
}}
import mypack.*;
class TestBalance
{
public static void main(String[] args)
{
/* Because Balance is public, you may use Balance class and call its
constructor. */
Balance test = new Balance("Kareem", -99.88); [Link]();
// you may also call show()
}
}
Prepared By : Linda R, Asst Professor in CSE, Dr. TTIT, KGF 8
Object Oriented Programming with JAVA (BCS306A)
As an experiment, remove the public specifier from the Balance class and then try
compiling TestBalance. As explained, errors will result.
Exceptions (Chapter 10)
• An exception is an abnormal condition that arises in a program at run time. (runtime
error)
• Java supports run-time error management to handle such errors.
Exception-Handling Fundamentals
• 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.
• Either way, at some point, the exception is caught and processed.
• Exceptions can be generated by the Java run-time system, or they can be manually
generated by user 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.
• How they work:
• 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.
• Your code can catch this exception (using catch) and handle it.
• System-generated exceptions are automatically thrown by the Java run-time system.
• To manually throw an exception, use the keyword throw. Any exception that is thrown
out of a method must be specified as such by a throws clause.
• Any code that must be executed after a try block completes is put in a finally block.
Syntax:
try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
Prepared By : Linda R, Asst Professor in CSE, Dr. TTIT, KGF 9
Object Oriented Programming with JAVA (BCS306A)
catch (ExceptionType2 exOb)
{
// exception handler for ExceptionType2
} //
...
finally
{
// block of code to be executed after try block ends
}
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.
• One branch is headed by Exception. This class is used for exceptional conditions that user
programs should catch and to create own custom exception types.
• There is an important subclass of Exception, called RuntimeException. Exceptions of this
type are automatically defined for the programs that you write and include things such
as division by zero and invalid array indexing.
• The other branch is topped by Error, which defines exceptions that are not expected to
be caught under normal circumstances by your program. Stack overflow is an example of
such an error.
Uncaught Exceptions
• This small program includes an expression that intentionally causes a divide-by-zero
error. What happens if exception is not caught?
class Exc0
{
public static void main(String[] args)
{ int d = 0;
int a = 42 / d;
}
}
Prepared By : Linda R, Asst Professor in CSE, Dr. TTIT, KGF 10
Object Oriented Programming with JAVA (BCS306A)
• In this example, we haven’t supplied any exception handlers of our own, so the exception
is caught by the default handler provided by the Java run-time system.
• The default handler displays a string describing the exception, prints a stack trace from
the point at which the exception occurred, and terminates the program.
Here is the exception generated when this example is executed:
Exception in thread "main" [Link]: / by
zero at [Link]([Link])
Using try and catch
Handling exceptions by user provides two benefits.
• It allows you to fix the error.
• It prevents the program from automatically stopping.
To 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 you wish to catch.
• The following program includes a try block and a catch clause that processes the
ArithmeticException generated by the division-by-zero error:
class Exc2
{
public static void main(String[] args)
{ int d, a; try
{ // monitor a block of code.
d = 0; a =
42 / d;
[Link]("This will not be printed.");
}
catch (ArithmeticException e)
{
// catch divide-by-zero error
[Link]("Division by zero.");
}
[Link]("After catch statement.");
}
}
Prepared By : Linda R, Asst Professor in CSE, Dr. TTIT, KGF 11
Object Oriented Programming with JAVA (BCS306A)
Displaying a Description of an Exception
• Throwable overrides the toString( ) method (defined by Object) so that it returns a
string containing a description of the exception.
• You can display this description in a println( ) statement by simply passing the exception
as an argument.
• For example, the catch block in the preceding program can be rewritten like this: class
Exc2
{
public static void main(String[] args)
{ int d, a; try
{ // monitor a block of code.
d = 0; a =
42 / d;
[Link]("This will not be printed.");
}
catch (ArithmeticException e)
{
// catch divide-by-zero error [Link](e);
}
[Link]("After catch statement.");
}
}
Multiple catch Clauses
• Sometimes more than one exception could be raised by a single piece of code.
• To handle this type of situation, you can 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.
• Example :
public class MultipleCatchDemo
{
public static void main(String[] args)
{
try
Prepared By : Linda R, Asst Professor in CSE, Dr. TTIT, KGF 12
Object Oriented Programming with JAVA (BCS306A)
{
int[] numbers = {1, 2, 3};
int result = numbers[1] / 0; // int result = numbers[1] / 1;
[Link](numbers[5]); // This will cause an ArrayIndexOutOfBoundsException
}
catch (ArithmeticException e)
{
[Link](e);
}
catch (ArrayIndexOutOfBoundsException e)
{
[Link](e);
}
[Link]("After try/catch blocks.");
}
}
Nested try statements:
public class NestedTryDemo
{
public static void main(String[] args)
{
try
{
int[] numbers = {1, 2, 3};
[Link]("Array element: " + numbers[1]);
try
{
int result = numbers[1] / 0; // Causes an ArithmeticException
[Link]("Result: " + result);
}
Prepared By : Linda R, Asst Professor in CSE, Dr. TTIT, KGF 13
Object Oriented Programming with JAVA (BCS306A)
catch (ArithmeticException e)
{
[Link](e);
}
}
catch (Exception e)
{
[Link]("Exception: Something went wrong.");
}
[Link]("End of program.");
}
}
throw
• So far, you have only been catching exceptions that are thrown by the Java run-time
system.
• However, it is possible for your program to throw an exception explicitly, using the
throw statement.
• The general form of throw is shown here:
throw ThrowableInstance;
• Here, ThrowableInstance must be an object of type Throwable or a subclass of
Throwable.
• Primitive/non-primitive types, such as int, char, String and Object, cannot be used as
exceptions.
• There are two ways you can obtain a Throwable object: using a parameter in a catch
clause or creating one with the new operator.
• The flow of execution stops immediately after the throw statement; any subsequent
statements are not executed.
public class ThrowDemo
{
// Method to check if a person is eligible to vote
static void checkEligibility(int age)
Prepared By : Linda R, Asst Professor in CSE, Dr. TTIT, KGF 14
Object Oriented Programming with JAVA (BCS306A)
{
if (age < 18)
{
// Throwing an exception if age is less than 18
throw new ArithmeticException("Not eligible to vote");
}
else
{
[Link]("Eligible to vote");
}
}
public static void main(String[] args)
{
try
{
checkEligibility(16); // This will cause an exception
}
catch (ArithmeticException e)
{
[Link]("Caught Exception: " + [Link]());
}
[Link]("End of program...");
}
}
throws
• If a method is capable of causing an exception that it does not handle, it must specify
this behaviour so that callers of the method can guard themselves against that
exception.
• You do this by including a throws clause in the method’s declaration.
• A throws clause lists the types of exceptions that a method might throw.
Prepared By : Linda R, Asst Professor in CSE, Dr. TTIT, KGF 15
Object Oriented Programming with JAVA (BCS306A)
• This is necessary for all exceptions, except those of type Error or RuntimeException, or
any of their subclasses.
• All other exceptions that a method can throw must be declared in the throws clause. If
they are not, a compile-time error will result.
This is the general form of a method declaration that includes a throws clause:
type method-name(parameter-list) throws exception-list
{
// body of method
}
• Here, exception-list is a comma-separated list of the exceptions that a method can throw.
public class ThrowsDemo
{
// Method that declares an exception static
void checkAge(int age) throws Exception
{
if (age < 18)
{
throw new Exception("Not eligible to vote");
}
else
{
[Link]("Eligible to vote");
}
}
public static void main(String[] args)
{
try
{
checkAge(16); // causes an exception
}
catch (Exception e)
{
[Link]("Caught Exception: " + [Link]());
Prepared By : Linda R, Asst Professor in CSE, Dr. TTIT, KGF 16
Object Oriented Programming with JAVA (BCS306A)
}
[Link]("End of program");
}
}
finally
• finally is a block of code that will be executed after a try /catch block has completed and
before the code following the try/catch block.
• The finally block will execute whether or not an exception is thrown.
• If an exception is thrown, the finally block will execute even if no catch statement
matches the exception.
• Useful for closing file handles and freeing up any other resources that might have been
allocated at the beginning of a method with the intent of disposing of them before
returning.
• The finally clause is optional. However, each try statement requires at least one catch or
a finally clause.
public class FinallyDemo
{
public static void main(String[] args)
{
try
{
[Link]("Inside try block");
int result = 10 / 0; // causes an ArithmeticException
}
catch (ArithmeticException e)
{
[Link](e);
}
finally
{
[Link]("Inside finally block");
// Cleanup code or code that needs to be executed
//regardless of exception
}
[Link]("End of program");
}
Prepared By : Linda R, Asst Professor in CSE, Dr. TTIT, KGF 17
Object Oriented Programming with JAVA (BCS306A)
Java’s Built-in Exceptions
• Inside the package [Link], Java defines several exception classes.
• The most general of these exceptions are subclasses of the standard type
RuntimeException.
• These exceptions need not be included in any method’s throws list.
• In Java, these are called unchecked exceptions because the compiler does not check to
see if a method handles or throws these exceptions.
• Table 1 lists the unchecked exceptions.
• Table 2 lists those exceptions defined by [Link] that must be included in a method’s
throws list.
• These are called checked exceptions.
Prepared By : Linda R, Asst Professor in CSE, Dr. TTIT, KGF 18
Object Oriented Programming with JAVA (BCS306A)
Prepared By : Linda R, Asst Professor in CSE, Dr. TTIT, KGF 19
Object Oriented Programming with JAVA (BCS306A)
Creating Your Own Exception Subclasses
• The Exception class does not define any methods of its own.
• But inherit those methods provided by Throwable.
• Thus, all exceptions, including those that you create, have the methods defined by
Throwable available to them.
• They are shown in Table 3. You may also wish to override one or more of these methods
in exception classes that you create.
• Exception defines four public constructors. Two support chained exceptions. The other
two are shown here:
Exception( )
Exception(String msg)
• The first form creates an exception that has no description. The second form lets you
specify a description of the exception.
The following example declares a new subclass of Exception and then uses that subclass to
signal an error condition in a method. It overrides the toString( ) method, allowing a
carefully tailored description of the exception to be displayed.
class MyException extends Exception
{
private int detail;
MyException(int a)
{
detail = a;
}
public String toString()
{
return "MyException[" + detail + "]";
}
}
class ExceptionDemo
{
static void compute(int a) throws MyException
{
[Link]("Called compute(" + a + ")");
if(a > 10)
throw new MyException(a);
[Link]("Normal exit");
}
Prepared By : Linda R, Asst Professor in CSE, Dr. TTIT, KGF 20
Object Oriented Programming with JAVA (BCS306A)
public static void main(String[] args)
{
try
{
compute(1);
compute(20);
}
catch (MyException e)
{
[Link]("Caught " + e);
}
}
}
Chained Exceptions
• Chained exceptions allows to associate one exception with another.
• It's useful when an exception is caused by another exception.
• You can essentially create a “chain” of exceptions, linking them together to provide a
more complete picture of an error.
• For example, imagine a situation in which a method throws an
ArithmeticException because of an attempt to divide by zero. However, the actual
cause of the problem was that an I/O error occurred, which caused the divisor to be
set improperly. Although the method must certainly throw an ArithmeticException,
since that is the error that occurred, you might also want to let the calling code know
that the underlying cause was an I/O error. Chained exceptions let you handle this,
and any other situation in which layers of exceptions exist.
• To allow chained exceptions, two constructors and two methods were added to
Throwable.
The constructors are shown here:
• Throwable(Throwable causeExc)
• Throwable(String msg, Throwable causeExc)
In the first form, causeExc is the exception that causes the current exception. The
second form allows you to specify a description at the same time that you specify a
cause exception.
The chained exception methods supported by Throwable are
Prepared By : Linda R, Asst Professor in CSE, Dr. TTIT, KGF 21
Object Oriented Programming with JAVA (BCS306A)
• getCause( )
• initCause( ).
The getCause( ) method returns the exception that underlies the current exception.
The initCause( ) method associates causeExc with the invoking exception and returns
a reference to the exception.
public class ChainedExceptionExample
{
public static void main(String[] args)
{
try {
method1();
}
catch (CustomException e)
{
[Link]("Caught: " + e);
[Link]("Original Cause: " + [Link]());
} }
static void method1() throws CustomException
{
try {
method2();
}
catch (ArithmeticException e)
{
throw new CustomException("Error in method1", e);
} }
static void method2()
{
int result = 10 / 0; // causes an ArithmeticException
}
}
class CustomException extends Exception
{
public CustomException(String message, Throwable cause)
{
Prepared By : Linda R, Asst Professor in CSE, Dr. TTIT, KGF 22
Object Oriented Programming with JAVA (BCS306A)
super(message, cause);
}
} Review
Questions:
1) Define an exception. What are the key terms used in exception handling? explain.
2) Write a program to raise an array index out of bound exception.
3) Write a program to raise a custom exception (user defined) for division by zero.
4) Write a program that contains one method that will throw an
IllegalAccessException and use proper exception handles so that the exception
should be printed.
5) How do you create your own exception class? Explain with a program. 6)
Demonstrate the working of a nested try block with an example.
Prepared By : Linda R, Asst Professor in CSE, Dr. TTIT, KGF 23