[Go to site: main page, start]

0% found this document useful (0 votes)
8 views15 pages

Java Packages and Exception Handling Guide

Uploaded by

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

Java Packages and Exception Handling Guide

Uploaded by

bharathbalaji701
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Object-Oriented Programming with JAVA: BCS306A

MODULE IV

MODULE IV
Contents
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, and finally.
 Java’s Built-in Exceptions.
 Creating Your Own Exception Subclasses, Chained Exceptions.

Packages
Package in Java is a mechanism to encapsulate a group of classes, sub-packages, and
interfaces. Packages are used for:
 Preventing naming conflicts. For example, there can be two classes with the
name Employee in two packages, [Link] and
[Link]
 Making searching/locating and usage of classes, interfaces, enumerations, and
annotations easier
 Providing controlled access: protected and default have package-level access
control. A protected member is accessible by classes in the same package and its
subclasses. A default member (without any access specifier) is accessible by
classes in the same package only.
 Packages can be considered as data encapsulation (or data-hiding).

All we need to do is put related classes into packages. After that, we can simply write an
import class from existing packages and use it in our program. A package is a container of a
group of related classes where some of the classes are accessible are exposed and others are
kept for internal purposes.
We can reuse existing classes from the packages as many times as we need it in our
program.

Department of Artificial Intelligence & Data Science, DBIT

1
Object-Oriented Programming with JAVA: BCS306A
MODULE IV

How do packages work?


Package names and directory structure are closely related. For example, if a package
name is college. staff. cse, then there are three directories, college, staff and cse such
that cse is present in staff and staff is present inside the college. Also, the
directory college is accessible through the CLASSPATH variable, i.e., the path of the
parent directory of the college is present in CLASSPATH. The idea is to make sure that
classes are easy to locate.
Package naming conventions
Packages are named in reverse order of domain names, i.e.,
[Link]. For example, in a college, the recommended convention is
college. [Link], college. [Link], [Link], etc.

Packages and Member Access


Classes and Packages are both means of encapsulating and containing the namespace and
scope of variables and methods. Packages act as a container for the classes and other
subordinate packages. Classes act as containers for the data and the code. The class is Java’s
smallest unit of abstraction. As it relates to the interplay between classes and packages, Java
addresses four categories of visibility for the 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 subclass

Member Access
Packages provide different levels of access protection

 Private – Within the class


 Public – universal access
 Protected – same package level and only for subclasses in different packages
 Default – only in the same packages, that is if we have not used as private, public, or
protected, then it will be considered as default.

Department of Artificial Intelligence & Data Science, DBIT

2
Object-Oriented Programming with JAVA: BCS306A
MODULE IV

Packages address 5 categories of visibility for class members

Types of Packages

Build in Packages
These packages consist of a large number of classes which are a part of Java API.
We can import these packages. Some of the commonly used built-in packages are:

 [Link]: Contains language support classes(e.g classes that define primitive data
types, math operations). This package is automatically imported.

 [Link]: Contains classes for supporting input/output operations.

 [Link]: Contains utility classes that implement data structures like Linked List,
Dictionary, and support; for Date / Time operations.

Department of Artificial Intelligence & Data Science, DBIT

3
Object-Oriented Programming with JAVA: BCS306A
MODULE IV

 [Link]: Contains classes for creating Applets.

 [Link]: Contain classes for implementing the components for graphical user
interfaces (like buttons, menus, etc).

 [Link]: Contains classes for supporting networking operations.


Example

 Import java. [Link]

 Import [Link].*

 Import [Link].*

 Import [Link].*

User Defined Packages

We have demonstrated all the programs with the help of the packages themselves, so
we will not discuss the creation of packages in this section, hoping that readers are
familiar with the creation of packages. Here we will discuss how we will have access to
one package method and instance variables in another package.

Demonstration of accessing methods defined in one package in another package

package package1;
public class A {
public void msg() {
[Link]("Hello");
}
}
package package2;
public class B {
public static void main(String[] args) {
package1.A obj = new package1.A(); //using fully qualified
name
[Link]();

}
}

Department of Artificial Intelligence & Data Science, DBIT

4
Object-Oriented Programming with JAVA: BCS306A
MODULE IV

A closer look at the program

 Here there are two different packages, package1 and package2


 Class A is in package1 and class B is in package2
 We can access the objects of class A which is in package1 in package 2 – class B
with the code package name. class name

How to Import one file from one package into another file in another package

We can import the file from one package into a class that belongs to another
package using the code import package name. class name

Demonstration of importing one file from one package into another file in
another package

package package3;
public class A {
public void msg() {
[Link]("Hello");
}
}
package package4;
import package3.A;
public class B {
public static void main(String[] args) {
A obj = new A();
[Link]();
}
}

A closer look at the program


 Here there are two packages named package3 and package4
 Class A is in package3
 Class B is in package4
 By using import, we could access the methods available in package3 in class B which
belongs to package4
 import package3.A, that I package name. class name will help us to do this job

Exceptions
In Java, an Exception is an unwanted or unexpected event, that occurs during the
execution of a program, i.e. at run time, that disrupts the normal flow of the program’s

Department of Artificial Intelligence & Data Science, DBIT

5
Object-Oriented Programming with JAVA: BCS306A
MODULE IV

instructions. Exceptions can be caught and handled by the program. When an exception
occurs within a method, it creates an object. This object is called the exception object. It
contains information about the exception, such as the name and description of the exception
and the state of the program when the exception occurred.

Major reasons why an exception Occurs


 Invalid user input
 Device failure
 Loss of network connection
 Physical limitations (out-of-disk memory)
 Code errors
 Opening an unavailable file

Types of Exceptions

Exceptions can be categorized in two ways:


1. Built-in Exceptions
 Checked Exception
 Unchecked Exception
2. User-Defined Exceptions

Built-in exception
Built-in exceptions are the exceptions that are available in Java libraries. These
exceptions are suitable to explain certain error situations.

Department of Artificial Intelligence & Data Science, DBIT

6
Object-Oriented Programming with JAVA: BCS306A
MODULE IV

 Checked Exceptions: Checked exceptions are called compile-time exceptions


because these exceptions are checked at compile-time by the compiler.

 Unchecked Exceptions: The unchecked exceptions are just opposite to the


checked exceptions. The compiler will not check these exceptions at compile
time. In simple words, if a program throws an unchecked exception, and even if
we didn’t handle or declare it, the program would not give a compilation error.
User Defined Exception
Sometimes, the built-in exceptions in Java are not able to describe a certain situation.
In such cases, users can also create exceptions, which are called ‘user-defined Exceptions’.

The advantages of Exception Handling in Java are as follows:


1. Provision to Complete Program Execution
2. Easy Identification of Program Code and Error-Handling Code
3. Propagation of Errors
4. Meaningful Error Reporting
5. Identifying Error Types

Understanding of Exception through a simple program

public class Exception {


public static void main(String[] args) {
int a=10;
int b=0;
int c=a/b;
[Link]("The value of c is " + c);
[Link]("End of Program");
}
}

Output:

A closer look at the program

Here the number 10 is divided by 0, answer should be infinity, in this case, all
our codes and logic are correct, but the execution didn’t happen. It is caught by Java.
lang as an Arithmetic Exception.

Department of Artificial Intelligence & Data Science, DBIT

7
Object-Oriented Programming with JAVA: BCS306A
MODULE IV

Java try and catch

The try statement allows you to define a block of code to be tested for errors while it
is being executed. The catch statement allows you to define a block of code to be executed if
an error occurs in the try block. The try-and-catch keywords come in pairs:

Demonstration of try and catch

package catchTry;
import [Link];
public class HandleError {
public static void main(String[] args) {
int a=0;
int b=0;
int c=0;
Random r= new Random();
for (int i=0; i<=150; i++ ) {
try {
b=[Link]();
c=[Link]();
a=3500/(b/c);
[Link](a);

}
catch(Exception e) {
[Link]("Error Encountered");
}
}
}
}

A closer look at the program

 [Link] will help us to generate the random numbers


 initialized the values of a, b, and c as 0
 In the for loop random numbers will be generated and perform the calculation,
a=3500/(b/c);
 When ever c is 0, the evaluation of a will through error
 Wherever we are expecting a computation error, we will write all those codes in the
try-catch block
try {b=[Link]();
c=[Link]();
a=3500/(b/c);

Department of Artificial Intelligence & Data Science, DBIT

8
Object-Oriented Programming with JAVA: BCS306A
MODULE IV

[Link](a);
}
catch(Exception e) {
[Link]("Error Encountered");
}
 The rest of the calculation, that is wherever the calculation is executed correctly we
will get the value of a, and wherever there is an error there will be a display
message "Error Encountered"

Multiple Catch Clauses

A try block can be followed by one or more catch blocks. Each catch block must
contain a different exception handler. So, if you have to perform different tasks at the
occurrence of different exceptions, use Java multi-catch block.

Points to remember

 At a time only one exception occurs and at a time only one catch block is executed.
 All catch blocks must be ordered from most specific to most general, i.e. catch for
Arithmetic Exception must come before catch for Exception.

Demonstration of Multiple Catch

public class MultilpeCatch {

public static void main(String[] args) {


try {
int a= [Link]; //[Link] will assign
the length as 0
[Link](" a " + a);
int b = 50/a;

int c[]= {1,8,9};

c[42]=99;

int d[]= {};


[Link](d[4]);

}
catch(ArithmeticException e) {
[Link]("Error encountered object" + e);

Department of Artificial Intelligence & Data Science, DBIT

9
Object-Oriented Programming with JAVA: BCS306A
MODULE IV

}
catch(ArrayIndexOutOfBoundsException e) {
[Link]("Error encountered");

[Link]("After try/catch blocks");

}
}
A Closer Look at the Program
 This program will cause a division by zero exception if it is started with no command
line arguments since a will be equal to 0
 Array C has only three elements, if we try to assign the 42nd index position value as
99 we are supposed to get the error since the array size is only 3.

[Link] --- In tamil

The key word finally

The keyword finally defines a block of code we use along with the try
keyword. It defines code that's always run after the try and any catch block before the
method is completed. The finally block executes regardless of whether an exception is
thrown or caught.

Demonstration of Multiple Try–catch, finally, and the Creation of our Exception


Subclass

package catchTry;

import [Link];
import [Link];
import [Link];
import [Link];

public class TryCatchFinallyYourOwnException {

public static void main(String[] args) {


int a=10;
int b=0;
int c=0;

Department of Artificial Intelligence & Data Science, DBIT

10
Object-Oriented Programming with JAVA: BCS306A
MODULE IV

//below two are unchecked exception, that is Run


time exception
try {

int array[]=null;
[Link](array[1]);
c=a/b;
}

catch(ArithmeticException e){
[Link]("Error occurred" + e);
}
catch(NullPointerException e){
[Link]("Error occurred" + e);
}
/*catch(ArithmeticException | NullPointerException
e){
[Link]("Error occurred" + e);
We can give both exceptions together in a
single catch
}*/
/*catch(Exception e){
[Link]("Error occurred");

}*/
//[Link](c);
//[Link]("End of program");
finally{
[Link](c);
[Link]("End of program");

}
//The below one is a checked exception
File file= new File("[Link]");
try {
FileInputStream fs = new FileInputStream(file);
//to read data from the file
}
catch(FileNotFoundException e){
[Link]("File not existing " + e );
[Link]();
//The above two lines of codes can be used
appropriately for printing the error
}
int i=0;

Department of Artificial Intelligence & Data Science, DBIT

11
Object-Oriented Programming with JAVA: BCS306A
MODULE IV

[Link]("Taking the value from the


user");
try(Scanner scanner = new Scanner([Link]))
{
i= [Link]();

}
[Link](i);

/*If we use a scanner we are supposed to close the


scanner
using the code [Link](). That is the best way to
use the resources
If we use the same in the try-catch block we need not
have to close the scanner.
*/
/* Next, we are demonstrating how a user can define his
exception*/
int balance=800;
int withdrawamount=700;
try {
if(balance < withdrawamount) {
throw new InsufficientFundException(withdrawamount -
balance);

}
else {
[Link]("Withdrawl is allowed OK");
}
}
catch(InsufficientFundException e){
[Link]("Insufficient fund");
}
}
}
package catchTry;

public class InsufficientFundException extends Exception {


int amount;
InsufficientFundException(int amt) {
amount=amt;
}
}

Department of Artificial Intelligence & Data Science, DBIT

12
Object-Oriented Programming with JAVA: BCS306A
MODULE IV

A Closer Look at the Program


 In the first try block we have given two codes, one related to math and one related to
array
 If the try block can find the arithmetic exception, then the null pointer exception print
statement will not be executed since the catch block has already caught the exception.
 If we give catch(Exception e){
[Link]("Error occurred");} without giving arithmetic
and null-pointer exception specifically still our catch block will catch the error, but it will not
specify the error is due to what.

 If We give catch(Exception e) before both the arithmetic and null pointer


exception it will through an error saying arithmetic and null pointer exception can’t be
caught since it is already caught by the catch(Exception e) block.
 Finally block will be executed irrespective of whether the remaining codes execute
well or not, or whether it shows an exception or not.
 Next, we want to read a txt file which is available in our local system with the code
File file= new File("[Link]") – That is we are creating an object for
the inbuilt class File
 This try-catch block try {
FileInputStream fs = new FileInputStream(file);
//to read data from the file
}
catch(FileNotFoundException e){
[Link]("File not existing " + e );
[Link]();
//The above two lines of codes can be used appropriately for printing the error
}
 FileInputStream fs = new FileInputStream(file) will help to
read the data from the file.
 If the file is not available in the local system, it will throw the error. To avoid that we
work with FileNotFoundException.
 This is considered as a checked exception in Java, This will happen during the
compile time.
 If we use a scanner we are supposed to close the scanner using the code
[Link](). That is the best way to use the resources.
 Instead of closing the scanner, the best way is to put the code in a try block. We need
not have to attach a catch block with this.
 Next, we demonstrate how a user can define our Exception class
 We want to throw an exception, that if the balance is less than the withdrawal request
amount, an insufficient fund exception should be thrown

Department of Artificial Intelligence & Data Science, DBIT

13
Object-Oriented Programming with JAVA: BCS306A
MODULE IV

 When we type throw new InsufficientFundException, it will show a popup to create a


class called ‘insufficientFundException, click that, and automatically a new exception
class will be created. We need not have to create on our own. This class that we have
created will be an extension of the superclass “Exception”

Java Keyword throw Vs throws

Factors Throw in Java Throws in Java


Purpose The 'throw' keyword is used to The 'throws' keyword is used in the
explicitly throw an exception from method signature to declare the
within a block of code or a method. exceptions that a method can potentially
throw.
Implementation The 'throw' keyword can only throw a The 'throws' keyword allows for the
single exception at a time. As such, it is declaration of multiple exceptions that a
not possible to throw multiple function could throw.
exceptions simultaneously with 'throw'.
Exception Type The 'throw' keyword can only The 'throws' keyword can be used to
propagate unchecked exceptions, declare both checked and unchecked
meaning that checked exceptions exceptions. For checked exceptions, the
cannot be propagated with 'throw'. 'throws' keyword must be followed by
the specific name of the exception class.
Syntax The 'throw' keyword is followed by the The 'throws' keyword is followed by the
instance variable. names of the exception classes.
Usage The 'throw' keyword should be used The 'throws' keyword should be used
within the body of a method. within the method signature.

[Link] – Link for throw Vs throws


[Link]
Demonstration of throw

public class Throw {


void voter(int age) {
if(age < 18) {
throw new ArithmeticException("You are not
eligible");
}
else{
[Link]("You are eligible");
}
}

Department of Artificial Intelligence & Data Science, DBIT

14
Object-Oriented Programming with JAVA: BCS306A
MODULE IV

public static void main(String[] args) {


Throw obj = new Throw();
[Link](19);
}
}
Note: Here We are throwing an arithmetic exception on our own

Department of Artificial Intelligence & Data Science, DBIT

15

You might also like