Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Module 4

This document provides an overview of packages and exception handling in Java. It explains the definition and types of packages, how to create user-defined packages, and the importance of access protection. Additionally, it covers exception handling concepts, techniques, and syntax, including the use of try-catch-finally blocks and the throw keyword.

Uploaded by

robog49037
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Module 4

This document provides an overview of packages and exception handling in Java. It explains the definition and types of packages, how to create user-defined packages, and the importance of access protection. Additionally, it covers exception handling concepts, techniques, and syntax, including the use of try-catch-finally blocks and the throw keyword.

Uploaded by

robog49037
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

MODULE 4

Packages and Exceptions

Packages in JAVA

Packages:

• A Package can be defined as a grouping of related types(classes, interfaces)


• A package represents a directory that contains related group of classes and interfaces.
• Packages are used in Java in order to prevent naming conflicts.
• Java package provides access protection.

There are two types of packages in Java.


1. Pre-defined Packages(built-in)
2. User defined packages

There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.

Defining a Package(User defined):

 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.

This is the general form of the package statement:


package pkg ;
pkg is the name of the package.
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.
 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.

To create a hierarchy of packages.


 separate each package name from the one above it by use of a period.
The general form of a multileveled package statement
package pkg1[.pkg2[.pkg3]];

A package hierarchy must be reflected in the file system of Java development system.

For example, a package declared as


package java.awt.image;

Finding Packages and CLASSPATH:

 Packages are mirrored by directories.


 The Java run-time system know where to look for packages that are created.
• First, by default, the Java run-time system uses the current working directory as its starting
point. Thus, if your package is in a subdirectory of the current directory, it will be found.
• Second, you can specify a directory path or paths by setting the
CLASSPATH environmental variable.

• Third, you can use the -classpath option with java and javac to specify the path
to your classes.

For example, consider the following package specification:


 package MyPack can be executed from a directory immediately above
MyPack ,
 or the CLASSPATH must be set to include the path to MyPack,
 or the -classpath option must specify the path to MyPack when the
program is run via java.
 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\Jav
Example: Package demonstration
package pack;
public class Addition
{

int x,y;
public Addition(int a, int b)
{

x=a;
y=b;
}
public void sum()
{

System.out.println("Sum :"+(x+y));
}

Save the above file with Addition.java

Access Protection
• Access protection defines actually how much an element (class, method, variable) is
exposed to other classes and packages.
• There are four types of access specifiers available in java:
1. Visible to the class only (private).
2. Visible to the package (default). No modifiers are needed.
3. Visible to the package and all subclasses (protected)
4. Visible to the world (publ
Example:
The following example shows all combinations of the access control modifiers. This example
has two packages and five classes. The source for the first package defines three classes:
Protection, Derived, and SamePackage.

Name of the package: pkg1


This file is Protection.java package
pkg1;

public class Protection


{

int n = 1;
private int n_priv = 2;
protected int n_prot = 3;
public int n_publ = 4;

public Protection()
{

System.out.println("base constructor");
System.out.println("n = " + n);
System.out.println("n_priv = " + n_priv);
System.out.println("n_prot = " + n_prot);
System.out.println("n_publ = " + n_publ);
}
}

This is file Derived.java:


package pkg1;

class Derived extends Protection


{

Derived()
{

System.out.println("Same package - derived (from base) constructor");


System.out.println("n = " + n);

/* class only
* System.out.println("n_priv = "4 + n_priv); */

System.out.println("n_prot = " + n_prot);


System.out.println("n_publ = " +n_publ);
}
}

This is file SamePackage.java package

pkg1;

class SamePackage
{

SamePackage()
{

Protection pro = new Protection(); System.out.println("same


package - other constructor"); System.out.println("n = " +
pro.n);

/* class only
* System.out.println("n_priv = " + pro.n_priv); */

System.out.println("n_prot = " + pro.n_prot);


System.out.println("n_publ = " + pro.n_publ);
}

Name of the package: pkg2


This is file Protection2.java:

package pkg2;

class Protection2 extends pkg1.Protection


{

Protection2()
{

System.out.println("Other package-Derived (from Package 1-Base)


Constructor");

/* class or package only


* System.out.println("n = " + n); */

/* class only
* System.out.println("n_priv = " + n_priv); */

System.out.println("n_prot = " + n_prot);


System.out.println("n_publ = " + n_publ);
}

This is file OtherPackage.java

package pkg2;

class OtherPackage
{

OtherPackage()
{

pkg1.Protection pro = new pkg1.Protection(); System.out.println("other

package - Non sub class constructor");


/* class or package only
* System.out.println("n = " + pro.n); */

/* class only
* System.out.println("n_priv = " + pro.n_priv); */

/* class, subclass or package only


* System.out.println("n_prot = " + pro.n_prot); */

System.out.println("n_publ = " + pro.n_publ);


}

If you want to try these t two packages, here are two test files you can use. The one for
package pkg1 is shown here:

/* demo package pkg1 */

package pkg1;

/* instantiate the various classes in pkg1


*/ public class Demo
{
public static void main(String args[])
{

Derived obj2 = new Derived();


SamePackage obj3 = new
SamePackage();
}
}

The test file for package pkg2 is

package pkg2;

/* instantiate the various classes in pkg2


*/ public class Demo2
{
public static void main(String args[])
{

Protection2 obj1 = new Protection2();


OtherPackage obj2 = new OtherPackage();
}

}
Importing Packages
 import statement is used to include certain classes, or entire packages, into visibility.
 Once imported, a class can be directly referred using its name.

This is the general form of the import statement:

import pkg1 [.pkg2].(classname | *);

 pkg1 is the name of a top-level package, and pkg2 is the name of a sub package inside the outer
package separated by a dot (.). There is no practical limit on the depth of a package hierarchy,
except that imposed by the file system.
 specify either an explicit classname or a star (*), which indicates that the Java compiler should
import the entire package.

Example:

package pack;

public class Addition


{

int x,y;
public Addition(int a, int b)
{

x=a;
y=b;
}
public void sum()
{

System.out.println("Sum :"+(x+y));
}

Save the above file with Addition.java

package pack;
public class Subtraction
{

int x,y;
public Subtraction(int a, int b)
{

x=a;
y=b;
}
public void diff()
{

System.out.println("Difference :"+(x-y));
}

Save the above file with Subtraction.java

There are three ways to use package in another package:

1. With fully qualified name.


class UseofPack
{

public static void main(String arg[])


{

pack.Addition a=new pack.Addition(10,15);


a.sum();
pack.Subtraction s=new
pack.Subtraction(20,15); s.difference();
}

2. import package.classname;
import pack.Addition;
import pack.Subtraction;
class UseofPack
{
public static void main(String arg[])
{

Addition a=new
Addition(10,15); a.sum();
Subtraction s=new Subtraction(20,15);
s.difference();
}

}
3. import package.*;
import
pack.*; class
UseofPack
{
public static void main(String arg[])
{

Addition a=new
Addition(10,15); a.sum();
Subtraction s=new Subtraction(20,15);
s.difference();
}

Exception handling

Introduction

An Exception, It can be defined as an abnormal event that occurs during program execution and disrupts the
normal flow of instructions. The abnormal event can be an error in the program.

Errors in a java program are categorized into two groups:

1. Compile- time errors occur when you do not follow the syntax of a programming language.
2. Run-time errors occur during the execution of a program.

Concepts of Exceptions

An exception is a run-time error that occurs during the exception of a java program.

Example :If you divide a number by zero or open a file that does not exist, an exception is raised.

In java, exceptions can be handled either by the java run-time system or by a user- defined code .
When a run-time error occurs, an exception is thrown.

The unexpected situations that may occur during program execution are:

 Running out of memory


 Resource allocation errors
 In ability to find files
 Problems in network connectivity

Exception handling techniques:

Java exception handling is managed via five keywords they are:


1. try:
2. catch.

3. throw.

4. throws.

5. finally.

Exception handling Statement Syntax

Exceptions are handled using a try-catch-finally construct, which has the Syntax:

try
{

<code>
}

catch(<exceptiontype1> <parameter1>)
{

//0 or more <statements>

finally
{

//finally block <statements>


}
1. try Block: The java code that you think may produce an exception is placed
with in a try block for a suitable catch block to handle the error.

If no exception occurs the execution proceeds with the finally block else it will look for the
matching catch block to handle the error.

Again if the matching catch handler is not found execution proceeds with the finally block and
the default exception handler throws an exception.

2. catch Block: Exceptions thrown during execution of the try block can be caught and
handled in a catch block. On exit from a catch block ,normal execution continues and the finally
block is executed (Though the catch block throws an exception).

3. finally Block: A finally block is always executed, regardless of the cause of exit from the try
block, or whether any catch block was executed. Generally, finally block is used for freeing
resources, cleaning up, closing connections etc.

Example:

The following is an array is declared with 2 elements. Then the code tries to access the 3rd element of the
array which throws an exception.

//FileName:ExcepTest.java

importjava.io.*;

public class ExcepTest

Public static void main(String args[])

try

Int a[]= new int[2]; System.out.println("Accesselementthree:"+a[3]);

catch(ArrayIndexOutOfBoundsException e)
{

System.out.println("Exceptionthrown:"+e);

System.out.println("Outoftheblock");

This would produce following result:

Exceptionthrown:java.lang.ArrayIndexOutOfBoundsException:3 Out of the block

Multiple catch Blocks:

A try block can be followed by multiple catch blocks .The syntax for multiple catch blocks looks like the
following:

try
{

//code
}

catch(ExceptionType1 e1)
{

//Catchblock
}

catch(ExceptionType2 e2)
{

//Catchblock
}

catch(ExceptionType3 e3)
{

//Catchblock
}

The previous statements demonstrate three catch blocks, but you can have any number of them
after a single try.

Example: Here is code segment showing how to use multiple try/catch statements.

class Multi_Catch

public static void main(String args[])

try

int a=args.length;

System.out. println(“a=”+a);

Int b=50/a;

Int c[]={1};

catch(ArithmeticException e)

System.out.println("Divisionbyzero");

catch(ArrayIndexOutOfBoundsException e)

System.out.println("arrayindexoutofbound");

OUTPUT

Division by zero

array index out of bound


Nested try Statements

 Just like the multiple catch blocks, we can also have multiple try blocks . These try blocks
may be written independently or we can nest the try blocks within each other, i.e., keep one
try-catch block within another try- block.The program structure for nested try statement is:

Syntax
try

//statements

//statements

try

//statements

//statements

catch(<exception_two> obj)

//statements

//statements

//statements

catch(<exception_two> obj)

//statements

 Consider the following example in which you are accepting two numbers from the
command line. After that, the command line arguments, which are in the string format, are
converted to integers.

 If the numbers were not received properly in a number format, then during the conversion
a NumberFormatException is raised otherwise the control goes to the next try block. Inside
this second try-catch block the first number is divided by the second number, and during the
calculation if there is any arithmetic error, it is caught by the inner catch block.

Example

class Nested_Try

public static void main(String args[])


{

try

int a = Integer.parseInt(args [0]);


int b = Integer.parseInt (args [1]);
int quot=0;

try

quot = a /b;
System.out.println(quot);
}

catch(ArithmeticException e)

System.out.println("dividebyzero");
}

catch(NumberFormatException e)

System.out.println("Incorrectargumenttype");
}

}
}

The output of the program is:

If the arguments are entered properly in the command prompt like:

OUTPUT
Java Nested_Try2 4 6
4

If the argument contains a string than the number:


Java Nested_Try 2 4 aa
Incorrect argument type

If the second argument is entered zero:


java Nested_Try2 4 0
divide by zero

throw Keyword

 throw keyword is used to throw an exception explicitly. Only object of throwable class or
its sub classes can be thrown.
 Program execution stops on encountering throw statement, and the closest catch
statement is checked for matching type of exception.

Syntax: throw ThrowableInstance

Creating InstanceofThrowableclass

There are two possible ways to get an instance of class Throwable,

1. Using a parameter in catch block.


2. Creating instance with new operator.

New NullPointerException("test");

This constructs an instance of NullPointerException with name test.

Example demonstrating throw Keyword

class Test
{

static void avg()


{

try
{

throw new ArithmeticException("demo");


}

catch(ArithmeticException e)
{

System.out.println("Exceptioncaught");
}

public static void main(String args[])


{

avg();
}

In the above example the avg() method throw an instance of Arithmetic Exception, which is
successfully handled using the catch statement.

throws Keyword

 Any method capable of causing exceptions must list all the exceptions possible during
its execution, so that anyone calling that method gets a
prior knowledge about which exceptions to handle. A method can do so by using the throws
keyword.

Syntax:

type method_name(parameter_list)

throws exception_list

//definition of method
}

NOTE: It is necessary for all exceptions, except the exceptions of type Error and
Runtime Exception, or any of their subclass.

Example demonstrating throws Keyword

class Test
{

static void check() throws ArithmeticException


{

System.out.println("Insidecheckfunction");
thrownewArithmeticException("demo");
}

public static void main(String args[])


{

try
{
check();
}
catch(ArithmeticException e)
{

System.out.println("caught"+e);
}

finally
 The finally clause is written with the try- catch statement. It is
guaranteed to be executed after a catch block or before the method
quits.

Syntax
try

//statements

catch(<exception> obj)
{

//statements
}

finally
{

//statements
}

Take a look at the following example which has a catch and a finally block. The
catch block catches the Arithmetic Exception which occurs for arithmetic error like
divide-by-zero. After executing the catch block the finally is also executed and
you get the out put for both the blocks
Example:

class Finally_Block

static void division()


{

try

int num = 34, den = 0;


int quot=num/den;
}

catch(ArithmeticExceptione)

System.out.println("Dividebyzero");
}

finally

System.out.println("Inthefinallyblock");
}

class Mypgm

public static void main(String args[])


{

Finally f=new Finally_Block();


f.division();
}

OUTPUT

Divide by zero
In the finally block
Java’s Built in Exceptions

Java defines several exception classes inside the standard package java.lang.

 The most general of these exceptions are subclasses of the standard type
RuntimeException. Since java.lang is implicitly imported in to all Java programs , most exceptions
derived from RuntimeException are automatically available.
Java defines several other types of
exceptions that relate to its various class
libraries .Followi ng is the list of Java
UncheckedRuntimeException

Exception Description

ArithmeticException Arithmeticerror,suchasdivide-by-zero.

ArrayIndexOutOfBoundsException Arrayindexisout-of-bounds.

Assignmenttoanarrayelementofaninc ompatibletype.
ArrayStoreException

ClassCastException Invalidcast.

IllegalArgumentException Illegalargumentusedtoinvokeamethod.

Illegal monitor operation, such as waiting on


IllegalMonitorStateException anunlockedthread.

Following is the list of Java Checked Exceptions Defined in java.lang.

Exception Description

ArithmeticException Arithmeticerror,suchasdivide-by-zero.

ArrayIndexOutOfBoundsException Arrayindexisout-of-bounds.

Assignmenttoanarrayelementofaninc ompatibletype.
ArrayStoreException

ClassCastException Invalidcast.

IllegalArgumentException Illegalargumentusedtoinvokeamethod.

Illegal monitor operation, such as waiting on


IllegalMonitorStateException anunlockedthread.
Environmentorapplicationisinincorrectstat e.
IllegalStateException

Requestedoperationnotcompatiblewithcurrentt
IllegalThreadStateException hreadstate.

IndexOutOfBoundsException Sometypeof index isout-of-bounds.

NegativeArraySizeException Arraycreatedwithanegativesize.

NullPointerException Invaliduseofanullreference.

Invalid conversion of a string to a numericformat.


NumberFormatException

SecurityException Attempttoviolatesecurity.

Attempt to index outside the bounds of astring.


StringIndexOutOfBounds

UnsupportedOperationException Anunsupportedoperationwasencountered.

Creating your own Exception Subclasses

 Here you can also define your own exception classes by extending Exception. These exception can
represents specific runtime condition of course you will have to throw them yourself, but once
thrown they will behave just like ordinary exceptions.
 When you define your own exception classes, choose the ancestor carefully. Most custom exception
will be part of the official design and thus checked, meaning that they extend Exception but not
Runtime Exception.

Example:Throwing User defined Exception

public class MyException extends Exception

String msg = "";intmarks=50; public


MyException()
{

publicMyException(Stringstr)
{

super(str);
}

Public String toString()


{

if(marks<=40)
msg = "You have failed";
if(marks>40)
msg = "You have Passed";

return msg;

class test

public static void main(String args[])

test t = new test();

t.add();

Public void add()

try

int i=0;

if(i< 40)

throw new MyException();


}

catch(MyException ee1)

System.out.println("Result:"+ ee1);

}OUTPUT

Result: You have Passed

Chained Exception
 Chained exceptions are the exceptions which occur one after another i.e.most of the time to response
to an exception are given by an application by throwing another exception.
 Whenever in a program the first exception causes an another exception, that is termed as Chained
Exception. Java provides new functionality for chaining exceptions.
 Exception chaining (also known as "nesting exception") is a technique for handling the exception,
which occur one after another i.e. most of the time is given by an application to response to an
exception by throwing another exception.
 Typically, the second exception is caused by the first exception. There fore chained exceptions help
the programmer to know when one exception causes another.
 The constructors that support chained exceptions in Throwable class are:

Throwable init Cause (Throwable) Throwable


( Throwable)
Throwable (String, Throwable)
Throwable getCause()

You might also like