Oops With Java Module 4
Oops With Java Module 4
MODULE 4
Syllabus:
Packages: Packages, Packages And Member Access, Importing Packages
Exception : 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
4.1 Packages
When we have more than one class in our program, usually we give unique names to classes. In a real-
time development, as the number of classes increases, giving unique meaningful name for each class will
be a problem. To avoid name-collision in such situations, Java provides a concept of packages. A package
is a collection of classes. The package is both a naming and a visibility control mechanism. You can
define classes inside a package that are not accessible by code outside that package. You can also define
class members that 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.
Java uses file system directories to store packages. For example, the .class file for any class 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. More than one file can include
the same package statement. The package statement simply specifies to which package the classes
defined in a file belong. It does not exclude other class in other files from being part of that same package.
One can create a hierarchy of packages. To do so, simply separate each package name from the one
above it by use of a period. The general form of a multileveled package statement is shown here:
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 [Link]; needs to be stored in java\awt\image in a
Windows environment. You cannot rename a package without renaming the directory in which the classes
are stored.
• By default, Java run-time uses current working directory as a starting point. So, if our package
is in a sub-directory of current working directory, then it will be found.
• We can set directory path using CLASSPATH environment variable.
• We can use –classpath option with javac and java to specify path of our classes.
Assume that we have created a package MyPackage. When the second two options are used, the class
path must not include MyPackage. It must simply specify the path to MyPackage. For example, in a
Windows environment, if the path to MyPackage is
C:\MyPrograms\Java\MyPackage
package MyPackage;
class Test
{ int a, b;
Test(int x, int y)
{ a=x;
b=y;
}
void disp()
{
[Link]("a= "+a+" b= "+b);
}
}
class PackDemo
{ public static void main(String args[])
{
Test t=new Test(2,3); [Link]();
}
}
Even a class has accessibility feature. A class can be kept as default or can be declared as public. When
a class is declared as public, it is accessible by any other code. If a class has default access, then it can
only be accessed by other code within its same package. When a class is public, it must be the only public
class declared in the file, and the file must have the same name as the class
Accessibility of members of the class can be better understood using the following table.
In a Java source file, import statements occur immediately following the package statement (if it exists)
and before any class definitions. The general form of the import statement is:
import pkg1[.pkg2].(classname|*);
For example,
import [Link]; import
[Link].*;
The star form may increase compilation time—especially if you import several large packages. For this
reason it is a good idea to explicitly name the classes that you want to use rather than importing whole
packages. However, the star form has absolutely no effect on the run-time performance or size of your
classes.
4
All of the standard Java classes included with Java are stored in a package called java. The basic language
functions are stored in a package inside of the java package called [Link]. Normally, you have to import
every package or class that you want to use, but since Java is useless without much of the functionality in
[Link], it is implicitly imported by the compiler for all programs. This is equivalent to the following line
being at the top of all of your programs:
import [Link].*;
If a class with the same name exists in two different packages that you import using the star form, the
compiler will remain silent, unless you try to use one of the classes. In that case, you will get a compile-
time error and have to explicitly name the class specifying its package.
The import statement is optional. Any place you use a class name, you can use its fully qualified name,
which includes its full package hierarchy. For example,
import [Link].*;
Can be written as –
class MyDate extends [Link]
{ …}
Exception Handling
An exception is an abnormal condition that arises in a code sequence at run time. In other words, an
exception is a run-time error. In computer languages that do not support exception handling, errors must
be checked and handled manually—typically through the use of error codes. This approach is as
cumbersome as it is troublesome. Java’s exception handling avoids these problems and, in the process,
brings run-time error management into the object oriented world.
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.
• finally: block should contain the code to be executed after finishing try-block.
try
{
// block of code to monitor errors
} catch
(ExceptionType1exOb)
{
// exception handler for ExceptionType1
} catch
(ExceptionType2exOb)
{
// exception handler for ExceptionType2
}
...
…. finally
{
// block of code to be executed after try block ends
}
Throwable
Exception Error
Customized Exception
RuntimeException Customized Exception
(User defined class to
(Automatically defined (User defined class to
handle own exception)
for programs) handle own exception)
Exception class is used for exceptional conditions that user programs should catch. We can inherit from
this class to create our 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.
6
Error class defines exceptions that are not expected to be caught under normal circumstances by our
program. Exceptions of type Error are used by the Java run-time system to indicate errors having to do
with the run-time environment, itself. Stack overflow is an example of such an error.
Any un-caught exception is handled by default handler. 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 above example is executed:
[Link]: / by zero at
[Link]([Link])
The stack trace displays class name, method name, file name and line number causing the exception. Also,
the type of exception thrown viz. ArithmeticException which is the subclass of Exception is displayed. The
type of exception gives more information about what type of error has occurred. The stack trace will always
show the sequence of method invocations that led up to the error.
class Exc1
{ static void subroutine()
{ int d = 0; int a =
10 / d;
}
public static void main(String args[])
{
[Link]();
}
}
The resulting stack trace from the default exception handler shows how the entire call stack is displayed:
[Link]: / by zero
at [Link]([Link]) at
[Link]([Link])
7
To handle run-time error, we need to enclose the suspected code within try block.
class Exc2
{ public static void main(String args[])
{ int d, a;
try
{ d = 0;
a = 42 / d;
[Link]("This will not be printed.");
} catch (ArithmeticException e)
{
[Link]("Division by zero.");
}
[Link]("After catch statement.");
}
}
Output:
Division by zero.
After catch statement.
The goal of most well-constructed catch clauses should be to resolve the exceptional condition and then
continue on as if the error had never happened.
import [Link];
class HandleError
{ public static void main(String args[])
{ int a=0, b=0, c=0;
Random r = new Random();
for(int i=0; i<10; i++)
{ try
{
b = [Link]();
c = [Link]();
a = 12345 / (b/c);
} catch (ArithmeticException e)
{
[Link]("Division by zero.");
a = 0;
}
8
The output of above program is not predictable exactly, as we are generating random numbers. But, the
loop will execute 10 times. In each iteration, two random numbers (b and c) will be generated. When their
division results in zero, then exception will be caught. Even after exception, loop will continue to execute.
class SuperSubCatch
{ public static void main(String args[])
{ try
9
{
int a = 0;
int b = 42 / a;
} catch(Exception e)
{
[Link]("Generic Exception catch.");
} catch(ArithmeticException e) // ERROR - unreachable
{
[Link]("This is never reached.");
}
}
}
The above program generates error “Unreachable Code”, because ArithmeticException is a subclass of
Exception.
When a method is enclosed within a try block, and a method itself contains a try block, it is considered to
be a nested try block.
class MethNestTry
{ static void nesttry(int a)
{ try
{ if(a==1) a = a/(a-
a);
if(a==2)
{ int c[] = { 1 };
c[42] = 99;
}
}catch(ArrayIndexOutOfBoundsException e)
{
[Link]("Array index out-of-bounds: " + e);
}
}
{
int a = [Link]; int
b = 42 / a;
[Link]("a = " + a); nesttry(a);
} catch(ArithmeticException e)
{
[Link]("Divide by 0: " + e);
}
}
}
D:\newjava>java NestTry
Divide by 0: [Link]: / by zero
4.3.7 throw
Till now, we have seen catching the exceptions that are thrown by the Java run-time system. 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;
class ThrowDemo
{ static void demoproc()
{ try
{ throw new NullPointerException("demo");
11
} catch(NullPointerException e)
{
[Link]("Caught inside demoproc: " + e);
}
}
Here, new is used to construct an instance of NullPointerException. Many of Java’s built-in run-time
exceptions have at least two constructors:
– one with no parameter and
– one that takes a string parameter
When the second form is used, the argument specifies a string that describes the exception. This string is
displayed when the object is used as an argument to print() or println(). It can also be obtained by a call
to getMessage(), which is defined by Throwable.
4.3.8 throws
If a method is capable of causing an exception that it does not handle, it must specify this behavior 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.
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.
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.
class ThrowsDemo
{ static void throwOne() throws IllegalAccessException
{
[Link]("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[])
{ try
{ throwOne();
12
} catch (IllegalAccessException e)
{
[Link]("Caught " + e);
}
Output:inside throwone
Caught [Link]:demo
4.3.9 finally
When exceptions are thrown, execution in a method takes a rather abrupt, nonlinear path that alters the
normal flow through the method. Sometimes it is even possible for an exception to cause the method to
return prematurely. This could be a problem in some methods. For example, if a method opens a file upon
entry and closes it upon exit, then you will not want the code that closes the file to be bypassed by the
exception-handling mechanism. The finally keyword is designed to address such situations.
The finally clause creates a block of code that will be executed after a try/catch block has completed and
before the next code of 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. Any time a method is about to return to the caller from inside a try/catch block, via an uncaught
exception or an explicit return statement, the finally clause is also executed just before the method returns.
The finally clause is optional. However, each try statement requires at least one catch or a finally clause.
class FinallyDemo
{
static void procA()
{
try
{
[Link]("inside procA"); throw
new RuntimeException("demo"); } finally
{
[Link]("procA's finally");
}
}
Output:
inside procA
procA’s finally
Exception caught
inside procB
procB’s finally
inside procC
procC’s finally
➢ Checked Exception
• The classes which directly inherit Throwable class except RuntimeException and Error are known
as checked exceptions
• Checked at compile time
e.g. IOException, SQLException etc.
• Checked exceptions are checked at compile-time.
➢ Unchecked Exception
• The classes which inherit RuntimeException are known as unchecked exceptions
[Link],NullPointerException, ArrayIndexOutOfBoundsException etc.
• Unchecked exceptions are not checked at compile-time, but they are checked at runtime
16
CloneNotSupportedException Attempt to clone an object that does not implement the Cloneable
interface.
Method Description
Throwable getCause( ) Returns the exception that underlies the current exception.
If there is no underlying exception, null is returned.
StackTraceElement[] Returns an array that contains the stack trace, one element
getStackTrace() at a time, as an array of StackTraceElement. The method at
the top of the stack is the last method called before the
exception was thrown. This method is found in the first
element of the array. The StackTraceElement class gives
your program access to information about each element in
the trace, such as its method name.
Throwable initCause(Throwable Associates causeExc with the invoking exception as a
causeExc) cause of the invoking exception. Returns a reference to the
exception.
void printStackTrace( PrintStream Sends the stack trace to the specified stream.
stream)
void setStackTrace(
Sets the stack trace to the elements passed in elements.
StackTraceElement
This method is for specialized applications, not normal
elements[ ]) use.
We may wish to override one or more of these methods in exception classes that we create. Two of the
constructors of Exception are:
Exception( )
Exception(String msg)
in order to create custom exception, we need to extend Exception class that belongs to [Link]
package.
Consider the following example, where we create a custom exception named
WrongFileNameException:
}
Note: We need to write the constructor that takes the String as the error message and it is called
parent class constructor
Or
Output
Caught
GeeksGeeks
20
In the above code, the constructor of MyException requires a string as its argument. The
string is passed to the parent class Exception’s constructor using super(). The
constructor of the Exception class can also be called without a parameter and the call to
super is not mandatory.
Chained Exceptions allows to relate one exception with another exception, i.e one
exception describes cause of another exception. 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.
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. Constructors Of Throwable class Which support chained exceptions
in java :
1. Throwable(Throwable cause) :- Where cause is the exception that causes the current
exception.
2. Throwable(String msg, Throwable cause) :- Where msg is the exception message
and cause is the exception that causes the current exception.
Methods Of Throwable class Which support chained exceptions in java :
1. getCause() method :- This method returns actual cause of an exception.
2. initCause(Throwable cause) method :- This method sets the cause for the calling
exception.
Lets understand the chain exception with the help of an example, here,
ArithmeticException was thrown by the program but the real cause of
exception was IOException. We set the cause of exception using initCause()
method.
import [Link];
[Link](new IOException("cause"));
throw ae;
}
else
{
[Link](a/b);
}
}
Output:
Note that Java’s exception-handling statements should not be considered a general mechanism for
nonlocal branching. If you do so, it will only confuse your code and make it hard to maintain.
Question Bank:
1. What do you mean by a package? How do you use it in a Java program? Explain with a program.
22