You are on page 1of 14

1 Module -4 BCS306A 2 Module -4 BCS306A

MODULE-4 Defining a Package(User defined):

PACKAGES: To create a package is quite easy: simply include a package command as the first statement
in a Java source file. Any classes declared within that file will belong to the specified
PACKAGES
package.

The package statement defines a name space in which classes are stored. If you omit the
A Package can be defined as a grouping of related types(classes, interfaces)
package statement, the class names are put into the default package, which has no name.
• A package represents a directory that contains related group of classes and interfaces.
• Packages are used in Java in order to prevent naming conflicts. This is the general form of the package statement:
• There are two types of packages in Java.
package pkg;
1. Pre-defined Packages (built-in)
2. User defined packages Here, pkg is the name of the package.

Pre-defined Packages (built-in): For example, the following statement creates a package called MyPackage:

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 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 classes in other files from being part of that same package.

Most real-world packages are spread across many files. You 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

The package keyword is used to create a package in java.


3 Module -4 BCS306A 4 Module -4 BCS306A

//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}

Finding Packages and CLASSPATH


package MyPack

 In order for a program to find MyPack, one of three things must be true.
 Either the program can be executed from a directory immediately above MyPack, or
 The -classpath option must specify the path to MyPack when the program is run via
java or
The CLASSPATH must be set to include the path to MyPack
When the second two options are used, the class path must not include MyPack, itself. It must
simply specify the path to MyPack.
For example, in a Windows environment, if the path to MyPack is
C:\MyPrograms\Java\MyPack
Then the class path to MyPack is
C:\MyPrograms\Java
 use one of the other two options described in the preceding section to specify the path
MyPack. [either –cp for temporarily setting path or CLASSPATH for permanent
setting of path]
5 Module -4 BCS306A 6 Module -4 BCS306A

PACKAGES AND MEMBER ACCESS }

There are four types of Java access modifiers:


Private: The access level of a private modifier is only within the class. It cannot be accessed public class Simple{
from outside the class. public static void main(String args[]){
Default: The access level of a default modifier is only within the package. It cannot be A obj=new A();
accessed from outside the package. If you do not specify any access level, it will be the
default. System.out.println(obj.data);//Compile Time Error

Protected: The access level of a protected modifier is within the package and outside the obj.msg();//Compile Time Error
package through child class. If you do not make the child class, it cannot be accessed from
}
outside the package.
}
Public: The access level of a public modifier is everywhere. It can be accessed from within
the class, outside the class, within the package and outside the package . 2) Default
If you don't use any modifier, it is treated as default by default. The default modifier is
accessible only within package. It cannot be accessed from outside the package. It provides
more accessibility than private. But, it is more restrictive than protected, and public.
Example of default access modifier:
In this example, we have created two packages pack and mypack. We are accessing the A class
from outside its package, since A class is not public, so it cannot be accessed from outside the
package.

//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
1) Private
package mypack;
The private access modifier is accessible only within the class.
import pack.*;
Simple example of private access modifier
class B{
In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the class, public static void main(String args[]){
so there is a compile-time error. A obj = new A();//Compile Time Error
class A{ obj.msg();//Compile Time Error
private int data=40; }
private void msg(){System.out.println("Hello java");} }
7 Module -4 BCS306A 8 Module -4 BCS306A

3) Protected
The protected access modifier is accessible within package and outside the package but through package pack;
inheritance only.
public class A{
The protected access modifier can be applied on the data member, method and constructor. It
public void msg(){System.out.println("Hello");}
can't be applied on the class.
}
It provides more accessibility than the default modifer.
//save by B.java
Example of protected access modifier:
In this example, we have created the two packages pack and mypack. The A class of pack
package is public, so can be accessed from outside the package. But msg method of this package mypack;
package is declared as protected, so it can be accessed from outside the class only through
inheritance. import pack.*;

//save by A.java
package pack; class B{

public class A{ public static void main(String args[]){

protected void msg(){System.out.println("Hello");} A obj = new A();

} obj.msg();

//save by B.java }

package mypack; }

import pack.*;
IMPORTING PACKAGES.
class B extends A{  Is a good mechanism for compartmentalizing diverse classes from each other.
 There are no core Java classes in the unnamed default package;
public static void main(String args[]){  All of the standard classes are stored in some named package.
B obj = new B();  Since classes within packages must be fully qualified with their package name or
names, it could become tedious to type in the long dot-separated package path name
obj.msg();
for every class you use.
}  Thus Java includes the import statement to bring certain classes, or entire packages,
into visibility.
}
Output:Hello
All of the standard Java classes included with Java are stored in a package called java.
4) Public
java.
The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers. The basic language functions are stored in a package inside of the java package called
java.lang.
Example of public access modifier
java.lang, is implicitly imported by the compiler for all programs, as Java is useless without
//save by A.java much of the functionality in it.
9 Module -4 BCS306A 10 Module -4 BCS306A

This is equivalent to the following line being at the top of all of your programs:
import java.lang.*; EXCEPTIONS:
If a class with the same name exists in two different packages that you import using the star
EXCEPTION-HANDLING FUNDAMENTALS
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 Exception Handling in Java is one of the powerful mechanism to handle the
Example: runtime errors so that the normal flow of the application can be maintained.

import MyPack.*;  Exception is an abnormal condition.

class TestBalance {  In Java, an exception is an event that disrupts the normal flow of the program. It is an
object which is thrown at runtime.
public static void main(String args[]) {
/* Because Balance is public, you may use Balance class and call its constructor. */ Exception Handling is a mechanism to handle runtime errors such

Balance test = new Balance("J. J. Jaspers", 99.88); ClassNotFoundException


test.show(); // you may also call show()
IOException
}}
SQLException

RemoteException, etc.

The java.lang.Throwable class is the root class of Java Exception hierarchy which is inherited
by two subclasses: Exception and Error.

 Java exception handling is managed via five keywords: try, catch, throw, throws, and
finally.

Keyword Description

try The "try" keyword is used to specify a block where we should place an
exception code. It means we can't use try block alone. The try block must be
followed by either catch or finally.

catch The "catch" block is used to handle the exception. It must be preceded by try
block which means we can't use catch block alone. It can be followed by finally
block later.

finally The "finally" block is used to execute the necessary code of the program. It is
executed whether an exception is handled or not.

throw The "throw" keyword is used to throw an exception.


11 Module -4 BCS306A 12 Module -4 BCS306A

 One branch is headed by Exception. This class is used for exceptional conditions that
throws The "throws" keyword is used to declare exceptions. It specifies that there
user programs should catch. This is also the class that you will subclass to create your
may occur an exception in the method. It doesn't throw an exception. It is own custom exception types. There is an important subclass of Exception, called
always used with method signature. RuntimeException.
 The other branch is topped by Error, which defines exceptions that are not expected to
be caught under normal circumstances by your program. Exceptions of type Error are
This is the general form of an exception-handling block: used by the Java run-time system to indicate errors having to do with the run-time
environment, itself.
Types of Java Exceptions
There are mainly two types of exceptions: checked and unchecked. An error is considered as
the unchecked exception. However, according to Oracle, there are three types of exceptions
namely:

Checked Exception

Unchecked Exception
Error

1) Checked Exception

The classes that directly inherit the Throwable class except RuntimeException and Error are
known as checked exceptions. For example, IOException, SQLException, etc. Checked
exceptions are checked at compile-time.

2) Unchecked Exception
EXCEPTION TYPES
The classes that inherit the RuntimeException are known as unchecked exceptions. For
All exception types are subclasses of the built-in class Throwable. Thus, Throwable is at the
top of the exception class hierarchy example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException,
etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime.

3) Error

Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError,


AssertionError etc.

UNCAUGHT EXCEPTIONS
The uncaught exceptions are the exceptions that are not caught by the compiler but
automatically caught and handled by the Java built-in exception handler.

This small program includes an expression that intentionally causes a divide-by-zero error.
13 Module -4 BCS306A 14 Module -4 BCS306A

public class TryCatchExample2 {

public static void main(String[] args) {


try
{
int data=50/0; //may throw exception
}
When the Java run-time system detects the attempt to divide by zero, it constructs a new //handling the exception
exception object and then throws this exception. This causes the execution of Exc0 to stop, catch(ArithmeticException e)
{
because once an exception has been thrown, it must be caught by an exception handler and
System.out.println(e);
dealt with immediately. }
System.out.println("rest of the code");
USING TRY AND CATCH }

 Java try block is used to enclose the code that might throw an exception. It must be }
used within the method. Output:
 If an exception occurs at the particular statement in the try block, the rest of the block
code will not execute. So, it is recommended not to keep the code in try block that java.lang.ArithmeticException: / by zero
will not throw an exception.
 Java try block must be followed by either catch or finally block. MULTIPLE CATCH CLAUSES
 In some cases, more than one exception could be raised by a single piece of code. To
Syntax of Java try-catch
handle this type of situation, you can specify two or more catch clauses, each catching
try{ a different type of exception.
//code that may throw an 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.
}catch(Exception_class_Name ref){}
 After one catch statement executes, the others are bypassed, and execution continues
after the try / catch block. The following example traps two different exception types:
Syntax of try-finally block
try{
//code that may throw an exception
}finally{}

Java catch block


 Java catch block is used to handle the Exception by declaring the type of exception
within the parameter.
 The declared exception must be the parent class exception ( i.e., Exception) or the
generated exception type. However, the good approach is to declare the generated
type of exception.
 The catch block must be used after the try block only. You can use multiple catch
block with a single try block.

TryCatchExample2.java
15 Module -4 BCS306A 16 Module -4 BCS306A

• In some situations, a part of a block may cause one error and the entire block itself may
cause another error. In such cases, exception handlers have to be nested.

Syntax:

try

statement 1;

statement 2;

try

statement 1;

statement 2;

}
Since ArithmeticException is a subclass of Exception, the first catch statement will handle all
catch(Exception e)
Exception-based errors, including ArithmeticException. This means that the second catch
statement will never execute. To fix the problem, reverse the order of the catch statements { } }

NESTED TRY STATEMENTS catch(Exception e)

• try statement can be nested. That is, a try statement can be inside the block of another { }
try.
• If no catch statement matches, then the Java run-time system will handle the
• What happens when control enters nested try statement? exception.

• Each time a try statement is entered, the context of that exception is pushed on • Here is an example that uses nested try statements:
the stack.
Example:
• If an inner try statement does not have a catch handler for a particular
class NestedExcep6 {
exception, the stack is unwound and the next try statement’s catch handlers are
inspected for a match. public static void main(String args[]){

• This continues until one of the catch statements succeeds, or until all of the try{
nested try statements are exhausted.
try{
Why use nested try block?
System.out.println("going to divide");
17 Module -4 BCS306A 18 Module -4 BCS306A

int b =39/0; • Primitive types, such as int or char, as well as non-Throwable classes, such as String
and Object, cannot be used as exceptions.
}catch(ArithmeticException e){System.out.println(e);}
• There are two ways you can obtain a Throwable object:
try{ • using a parameter in a catch clause, or

int a[]=new int[5]; • creating one with the new operator.


• Syntax
a[5]=4;

}catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}

System.out.println("other statement); • Example

}catch(Exception e){System.out.println("handeled");}

System.out.println("normal flow..");
Example:
}
public class TestThrow1{
}
static void validate(int age){
Output if(age<18)

going to divide throw new ArithmeticException("not valid");


else
java.lang.ArithmeticException: / by zero
System.out.println("welcome to vote");
java.lang.ArrayIndexOutOfBoundsException: 5
}
other statement public static void main(String args[]){

normal flow.. validate(13);


System.out.println("rest of the code...");
throw }

• Used to throw an exception explicitly, other than catching exceptions that are thrown }
by the Java run-time system.
• Either checked or uncheked exception in java can be used by throw keyword. The Output:
throw keyword is mainly used to throw custom exception.
Exception in thread main java.lang.ArithmeticException:not valid
• The general form of throw is
throw ThrowableInstance; throws
• ThrowableInstance must be an object of type Throwable or a subclass of Throwable.
 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.
19 Module -4 BCS306A 20 Module -4 BCS306A

Second, main( ) must define a try/catch statement that catches this exception.
 You do this by including a throws clause in the method’s declaration. The corrected example is shown here:
 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, // This is now correct.
or any of their subclasses. [checked exception only need to be declared]
 All other exceptions[checked exception ]that a method can throw must be declared in class ThrowsDemo {
the throws clause.
 If they are not, a compile-time error will result. static void throwOne() throws IllegalAccessException {

General form of a method declaration that includes a throws clause: System.out.println("Inside throwOne.");

type method-name(parameter-list) throws exception-list throw new IllegalAccessException("demo");


{
// body of method }
}
public static void main(String args[]) {
 exception-list is a comma-separated list of the exceptions that a method can throw.
Following is an example of an incorrect program that tries to throw an exception that it does try {
not catch. Because the program does not specify a throws clause to declare this fact, the
throwOne();
program will not compile.
} catch (IllegalAccessException e) {

System.out.println("Caught " + e);


// This program contains an error and will not compile.
}
class ThrowsDemo {
}}
static void throwOne() {

System.out.println("Inside throwOne.");

throw new IllegalAccessException("demo");

public static void main(String args[]) {

throwOne();

} }

To make this example compile, you need to make two changes.

First, you need to declare that throwOne( ) throws IllegalAccessException.


21 Module -4 BCS306A 22 Module -4 BCS306A

 The finally clause is optional.


 However, each try statement requires at least one catch or a finally clause.
 If a finally block is associated with a try, the finally block will be executed upon
conclusion of the try
public class TestFinallyBlock2{
public static void main(String args[]){

try {

System.out.println("Inside try block");

//below code throws divide by zero exception


int data=25/0;

finally System.out.println(data);
}
 When exceptions are thrown, execution in a method takes a rather abrupt, nonlinear
//handles the Arithmetic Exception / Divide by zero exception
path that alters the normal flow through the method.
catch(ArithmeticException e){
 It is even possible for an exception to cause the method to return prematurely.
System.out.println("Exception handled");
 For example, if a method opens a file upon entry and closes it upon exit, then you will
System.out.println(e);
not want the code that closes the file to be bypassed by the exception-handling
}
mechanism.
//executes regardless of exception occured or not
 creates a block of code that will be executed after a try/catch block has completed and
finally {
before the code following the try/catch block.
System.out.println("finally block is always executed");
 The finally block will execute whether or not an exception is thrown.
}
 Java finally block is always executed whether exception is handled or not.
 If an exception is thrown, the finally block will execute even if no catch statement
System.out.println("rest of the code...");
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.
 This can be useful for closing file handles and freeing up any other resources that might The finally keyword is designed to address this contingency
have been allocated at the beginning of a method with the intent of disposing of them
before returning.
23 Module -4 BCS306A 24 Module -4 BCS306A

JAVA’S BUILT-IN EXCEPTIONS class JavaException{

 The standard package java.lang, Java defines several exception classes. public static void main(String args[]){

 The most general of these exceptions are subclasses of the standard type try{
RuntimeException. // throw is used to create a new exception and throw it.
 These exceptions need not be included in any method’s throws list. throw new MyException();
 In Java, these are called unchecked exceptions because the compiler does not check to } catch(MyException e){ System.out.println(e) ;
see if a method handles or throws these exceptions.
}}}
 The unchecked exceptions defined in java.lang are listed below
class MyException extends Exception{
int a;
MyException() {
}
public String toString(){
return ("user defined Exception ") ;
}}
Output:
user defined Exception

CREATING YOUR OWN EXCEPTION SUBCLASSES


Although Java’s built-in exceptions handle most common errors, you will probably want to
 create your own exception types to handle situations specific to your applications. This is quite
 Checked Exceptions
easy to do: just define a subclass of Exception (which is, of course, a subclass of Throwable).

The Exception class does not define any methods of its own. It does, of course, inherit those
methods provided by Throwable

class MyException extends Exception {

private int detail;

MyException(int a) {

detail = a;

public String toString() {


25 Module -4 BCS306A 26 Module -4 BCS306A

return "MyException[" + detail + "]";

public class Main {

static void compute(int a) throws MyException {

System.out.println("Called compute(" + a + ")");

if (a > 10)

throw new MyException(a);

System.out.println("Normal exit");

public static void main(String args[]) {

try {

compute(1);

compute(20);

} catch (MyException e) {

System.out.println("Caught " + e);


Table 10-3 The Methods Defined by Throwable
}} }

CHAINED EXCEPTIONS.
 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 :
27 Module -4 BCS306A

-Throwable(Throwable cause) :- Where cause is the exception that causes the


current exception.
-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 :

-getCause() method :- This method returns actual cause of an exception.


-initCause(Throwable cause) method :- This method sets the cause for the calling
exception.
Example of using Chained Exception:
// Java program to demonstrate working of chained exceptions
public class ExceptionHandling
{
public static void main(String[] args)
{
try
{
// Creating an exception
NumberFormatException ex =
new NumberFormatException("Exception");

// Setting a cause of the exception


ex.initCause(new NullPointerException(
"This is actual cause of the exception"));

// Throwing an exception with cause.


throw ex;
}

catch(NumberFormatException ex)
{
// displaying the exception
System.out.println(ex);

// Getting the actual cause of the exception


System.out.println(ex.getCause());
}
}
}
Output:
java.lang.NumberFormatException: Exception
java.lang.NullPointerException: This is actual cause of the exception

You might also like