0% found this document useful (0 votes)
15 views56 pages

Unit V

Uploaded by

anandhi.k
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views56 pages

Unit V

Uploaded by

anandhi.k
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 56

Unit V

Packages and Interfaces


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.
 Define classes inside a package that are not accessible by code outside that package.
 Also define class members that are only exposed to other members of the same
package.
Defining 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 omit the package statement, the class names are put into the default package, which has no
name.
 package pkg;
 Here, pkg is the name of the package.
 For example, the following statement creates a package called MyPackage.
 package MyPackage;
A Short Package Example
Contd…
 Next, compile the file.
 Make sure that the resulting .class file is also in the MyPack directory.
 Then, try executing the AccountBalance class, using the following command line:
 java MyPack.AccountBalance
 Remember, will need to be in the directory above MyPack when execute this command.
 As explained, AccountBalance is now part of the package MyPack.
 This means that it cannot be executed by itself.
 That is, cannot use this command line:
 java AccountBalance
 AccountBalance must be qualified with its package name
Access Protection
 Classes and packages are both means of encapsulating and containing the name space and
scope of variables and methods.
 Packages act as containers for classes and other subordinate packages.
 Classes act as containers for data and code.
 The class is Java’s smallest unit of abstraction.
Contd…
 Because of the interplay between classes and packages, 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
Importing Packages
 In a Java source file, import statements occur immediately following the package statement
(if it exists) and before any class definitions.
 This is the general form of the import statement:
 import pkg1[.pkg2].(classname|*);
 import java.util.Date;
 import java.io.*;
example
example
Interfaces
 An interface is defined much like a class. This is the general form of an interface
Implementing Interfaces
Contd…
Contd…
Contd…
Contd…
Exception Handling
Using try and catch
Multiple catch Clauses
Contd…
 When you use multiple catch statements, it is important to remember that exception
subclasses must come before any of their superclasses.
 This is because a catch statement that uses a superclass will catch exceptions of that
type plus any of its subclasses.
 Thus, a subclass would never be reached if it came after its superclass. Further, in
Java, unreachable code is an error
example
Contd…
 If you try to compile this program, you will receive an error message stating that the
second catch statement is unreachable because the exception has already been
caught.
 Since ArithmeticException is a subclass of Exception, the first catch statement will
handle all Exception-based errors, including ArithmeticException.
 This means that the second catch statement will never execute.
Nested try Statements
 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.
Contd…
 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
example
example
throw
 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;

 ThrowableInstance must be an object of type Throwable or a subclass of Throwable


example
Contd…
 This program gets two chances to deal with the same error. First, main( ) sets up an
exception context and then calls demoproc( ).
 The demoproc( ) method then sets up another exceptionhandling context and
immediately throws a new instance of NullPointerException, which is caught on the
next line. The exception is then rethrown.
 Here is the resulting output:
Caught inside demoproc.
Recaught: java.lang.NullPointerException: demo
Contd…
 Here, new is used to construct an instance of NullPointerException.
 Many of Java’s builtin 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.
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.
 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
Contd…
 Syntax:
 type method-name(parameter-list) throws exception-list
{ // body of method }
Contd…
finally
 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.
Contd…
 This can be 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.
example
Java’s Built-in Exceptions
 Inside the standard package java.lang, Java defines several exception classes
 The most general of these exceptions are subclasses of the standard type
RuntimeException.
 In the language of Java, these are called unchecked exceptions because the compiler
does not check to see if a method handles or throws these exceptions.
Unchecked Runtime ExceptionS
Java’s Checked Exceptions
Creating Your Own Exception Subclasses
 Create your own exception types to handle situations specific to your applications.
 Just define a subclass of Exception.
 The Exception class does not define any methods of its own. It does, of course,
inherit those methods provided by Throwable.
 Thus, all exceptions, including those that you create, have the methods defined by
Throwable available to them.
Contd…
 Exception defines four constructors.
 Exception( )
 Exception(String msg)
 Two were added by JDK 1.4 to support chained exceptions
output
Chained Exceptions
 The chained exception feature allows you to associate another exception with an
exception.
 This second exception describes the cause of the first exception.
Contd…
 To allow chained exceptions, two constructors and two methods were added to
Throwable.
 The constructors:
◦ Throwable(Throwable causeExc) -causeExc is the exception that causes the current exception
◦ Throwable(String msg, Throwable causeExc)-specify a description at the same time that you
specify a cause exception
Contd…
 Methods:
 Throwable getCause( ) -returns the exception that underlies the current exception.
If no underlying exception, null is returned.
 Throwable initCause(Throwable causeExc)-associates causeExc with the invoking
exception and returns a reference to the exception. You can call initCause( ) only
once for each exception object.
Using Exceptions
 Exception handling provides a powerful mechanism for controlling complex
programs that have many dynamic run-time characteristics.
 It is important to think of try, throw, and catch as clean ways to handle errors and
unusual boundary conditions in your program’s logic.
 Unlike some other languages in which error return codes are used to indicate failure,
Java uses exceptions
Contd…
 Thus, when a method can fail, have it throw an exception. This is a cleaner way to
handle failure modes.
 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.

You might also like