0% found this document useful (0 votes)
51 views50 pages

OOPTJ Unit4 Packages, Exception Handling

Uploaded by

rahulswarna027
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)
51 views50 pages

OOPTJ Unit4 Packages, Exception Handling

Uploaded by

rahulswarna027
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
You are on page 1/ 50

Unit 4

Packages
Introduction

 Java is purely object-oriented programming language; Therefore, it contains


number of classes and interfaces.
 In Java, every program is a class, which also uses other classes and interfaces
defined by user or defined in java standard library.
 One of the main objectives of the OOP is to reuse code that already exists.
 There are two ways to reuse the existing code:
 One way for achieving this is by extending the classes and implementing the
interfaces.
 Another way is packages, Java provides a mechanism to partition the classes
into smaller chunks. This mechanism is the package. The package is
container of classes and interfaces.
 The classes and interfaces that are related can be grouped into packages and sub
packages.
 The programs or classes that we create must be in a package.
 A large number of packages and sub packages are contained in java package.
 If the package is not been created by the user then the classes and interfaces are
automatically placed in a default package by the compiler.

Packages as Name Space


 One of the advantages of grouping the classes and interfaces into packages is that
a package will address name space collision, which occurs when use same name
for multiple classes.
 Hence every time we need to use different name for our program, which is
tedious.
 If a number of programmers are working on project, there will be a possibility that
some of them may use same names for classes and interfaces which will create
ambiguity.
 Same names can be used in other packages without any ambiguity.
 Example: If a program named “Test.java” is already existing in our current
working directory, then if you try to use the same name for another program we
get the following error: Test.java already exists. Do you want to replace it?
Benefits of packages
 The classes in the packages can be easily reused.

 In the packages, classes are unique compared with other classes in the other
packages. Hence resolves the name space collision.

 Packages provide a way to hide classes thus prevent classes from accessing by
other programs.

 Packages also provide way to separate "design" from "coding".


Defining Package

 A package is a container of classes and interfaces that are related.


 The packages is defined with keyword ‘package’ followed by package name and a
semicolon at the end.
 The package contains classes , interface and sub packages as members.
 All the members of the package must have unique names.
 For example java package contains util, io, awt, and applet as its members.
 A package also provides access control mechanism. If the class is declared as
public in a package then it can be accessed in any other package.

Simple name and qualified name


 According to the java convention package name is written in lower case only.
Example: java.util.*;

 A package that is not part of any other package can have a simple name. Example:
java, and javax

 A package that is part of another package consists of a combination of names


separated by dot (.) operator can have a qualified name. Example:
package pack1.pack2.pack3;
Importing packages and classes

 All the java programs usually refer one or more packages in the source code.

 We can use the packages in the program using the keyword ‘import’.
 If a program need several classes of a package, then it is better to import the entire
package.
This can be done as follow: import java.util.*;
Importing class in programs
 Packages are organized in hierarchical structure that means a package can contain
another package, which in turn contains several classes for performing different
tasks.
 There are two ways to import the classes of the packages.
1. fully qualified class name- this is done by specifying package name
containing the class and appending the class to it with dot (.) operator.
Example: java.util.StringTokenizer(); Here, "java.util" is the package
and "StringTokenizer()" is the class in that package. This is used when
we want to refer to only one class in a package.
2. import statement –this is used when we want to use a class or many
classes in many places in our program. Example: (1) import java.util.*;
Example : import java.util.StringTokenizer;
Example program : Using the fully qualified name
RandomTest.java
class RandomTest
{
public static void main(String
arg[])
{
java.util.Random rn=new java.util.Random();
int n=rn.nextInt(50);
System.out.println("Random number is:"+n);
}
}
Example Program : Using import statement

RandomTest.java
import java.util.Random;
class RandomTest
{
public static void main(String arg[])
{
Random rn=new
Random();
int n=rn.nextInt(50);
System.out.println("Random number is:"+n);
}
}

User-defined packages and classes

 One of the important feature of java programming is it allows programmer to


build his own packages and classes when ever required.
 We can save packages and classes in a directory, and from there we can access to
the program when ever required using the import statement.
 The following points should be taken care while constructing a folder for user’s
own package.
 The folder name must be same as package name.
 Create the required classes to be imported and save them in the folder.
 The application program must be saved out side this folder; that means the
package and application program must be in the same folder.
package arith;
public class MyMath
{
public void add(int x, int y)
{
System.out.println("Sum is:"+(x+y));
}

public void sub(int x, int y)


{
System.out.println("Subtraction is:"+(x-y));
}

public void mul(int x, int y)


{
System.out.println("Product is:"+(x*y));
}

public void div(int x, int y)


{
System.out.println("Quotient is:"+(x/y));
}
}

Importing arith package


import arith.*;
class Test
{
public static void main(String arg[] )
{
MyMath m=new MyMath(); //create object from class
//call methods

m.add(12,13);
m.sub(23,4);
}
}
Adding a class to a Package
It is simple to add a class to already existing package. Consider the following
Package:

A.java
package p1;
public class A
{ // body of the class
}

Here, p1 is a package contains one public class by the name A. Suppose if we


want to add another class B to this package. This can be done as follows:
B.java
package p1;
public class B
{ // body of the class
}

Path and CLASSPATH


 If the java programs need to run on Command Prompt, the programmer must
know how to set PATH and CLASSPATH.
 Otherwise, when you compile java program, you would get the output as “javac
is not recognized as an internal or external command”
 The PATH is an environment variable used to locate where the java compiler
(javac) is present.
 The CLASSPATH is also another environment variable, it is used by java
runtime system or ClassLoader to locate where .class files defined by the user
will be available.
 The javac compiles the source program and generates .class file (Byte Code),
which will be interpreted by the java interpreter (JVM) for execution of
program.
There are two ways to set the Path and CLASSPATH
 Set on command prompt.
 Set using the environment variable

Set on command prompt


 C:\Users>set path=C:\Program Files (x86)\Java\jdk1.7.0_80\bin
 C:\Users>javac C:\Users\JLP\R19\Test2.java
 C:\Users\JLP\R19>java Test2
o Sum in sub class is:5
 C:\Users >set CLASSPATH=C:\Users\\JLP\R19
 Set using the environment variable
 Right Click on My Computer
 Select properties
 Select the System Advanced System settings
 Select environmental variable
 Go to System variables and select Path and CLASSPATH, if existing.
 Click on the edit button to set the path with java compilers path, and set the
.class files folder to CLASSPATH respectively.

Access Control

 Packages are containers of sub-packages, classes, and interfaces. The


encapsulation of related classes in package addresses name space collision and
access protection.
 The visibility of an element is specified by the access specifiers: public, private,
and protected and also the package in which it resides. The visibility of an
element is determined by its visibility within class, and visibility within the
package.
 If any members explicitly declared as "public", they are visible everywhere,
including in different classes and packages.
 "private" members are accessed by only other members of its class. A private
member is unaffected by its membership in a package.
 A member specified as "protected" is accessed within its package and to all
subclasses.
 But, the classes and interfaces themselves can have only two access modifiers
when declared outside any other class.
1) public
2) default (when no access modifier is specified)

Note: Nested interfaces and classes can have all access modifiers.

We cannot declare class/interface with private or protected access modifiers.


java.lang package and its classes

 Java.lang package is imported into every java program by default.


 The programmer need not use import statement to import it into the source code.
 This package contains classes and interfaces that are essential to develop java
programming.
 The most important classes are : Object and Class
 The Object class is the super class for all the classes.
 The instances of ‘Class’ will be used at run-time.
 This also provides wrapper classes for all primitive data types such as Integer,
Character, Double, Float, Long, Byte, Short, and Boolean which are used to
represent a value as an Object. Ex: Integer i=new Integer(4);
 It provides Math class, which is used to perform mathematical operations such
min, max, sqrt, abs, etc;
 It provides Throwable which is the super class for all the Exceptions and Errors.
 It also provides the Thread class to perform multithreading.
 It also provides String and StringBuffer class to work with strings.
 Click here to see all the classes and interfaces in java.lang
 Example Program
 We can see all the packages at the following link
https://docs.oracle.com/javase/8/docs/api/

Object Class

 The Object class is one of the important classes of java because it is the super
class of all classes.

 The class has one constructor and 11 methods.


 All the java classes can inherit these methods.
 The constructor is Object()

Modifier type Method - Description


protected Object clone() - Creates and returns a copy of this object.
boolean equals(Object obj) - Indicates whether some other object is "equal
to" this one.
protected void finalize() - Called by the garbage collector on an object when
garbage collection determines that there are no more references to
the object.
Class<?> getClass() - Returns the runtime class of this Object.
int hashCode() - Returns a hash code value for the object.
void notify() - Wakes up a single thread that is waiting on this object's
monitor.
void notifyAll() - Wakes up all threads that are waiting on this object's
monitor.
String toString() - Returns a string representation of the object.
void wait() - Causes the current thread to wait until another thread
invokes the notify() method or the notifyAll() method for
this object.
void wait - (long timeout)Causes the current thread to wait until either
another thread invokes the notify() method or the notifyAll()
method for this object, or a specified amount of time has elapsed.
void wait(long timeout, int nanos) - Causes the current thread to wait
until another thread invokes the notify() method or the notifyAll()
method for this object, or some other thread interrupts the current
thread, or a certain amount of real time has elapsed.
Example program

Enumeration
 The enumeration facility is added with Java 5.
 In other programming languages such as C and C++, we have been using enumeration.
 In C and C++ enumeration is just a named constant. The Enumeration in java is
different from C and C++. In Java, we can also add variables, methods and
constructors to it.
 In the java ‘enum’ keyword is used which has the status like class, but with limited
facilities.
 Like class, enum type also has instance, constructor, methods, and inner classes.
 The instance is not done with new operator.
 The instance are declared like primitive data types.
Declaration of enum in java
enum week
{
SUNDAY,MONDAY;
}
week w=week.SUNDAY;
//here w is the instance of the enum
 Enum type encapsulates fixed set of constants, any other constant cannot be added
later.
 The enum can be declared inside or out side the class.
 The following pointes must be noted for declaration:
 The new operator will not be used for declaration
 The enum type reference is required whenever the member is declared as in the
2nd line.
 The values that variable w may have is one of the constants declared in the
declaration. It cannot have any value other than the ones in the declaration.

Members of enum

 Members declared in the enum declaration

 Members inherited from super class enum

 Constants declared in enum by default public and final.


Methods of enum

The enum has following methods:


 values() method can be used to return all values present inside enum.
 Order is important in enums.

 By using ordinal() method, each enum constant index can be found, just like
array index which starts with 0.

 valueOf() method returns the enum constant of the specified string value, if
exists.
Example program with constants and methods

EnumTest.java
enum Color
{
RED,GREEN,BLUE,YELLOW,VIOLET;
}
class EnumTest
{
public static void main(String arg[])
{
for(Color c:Color.values())
{
System.out.println(c+"is at index:"+c.ordinal()); }
System.out.println("The value of yellow is :"+Color.valueOf("YELLOW"));
}
}

output

C:\Users\JP>javac TestEnum.java
C:\Users\\JP>java TestEnum
RED is at index:0
GREEN is at index:1
BLUE is at index:2
YELLOW is at index:3
VIOLET is at index:4
The value of yellow is :YELLOW
General enum declaration

 The general declaration of enum begin with access modifier followed by enum
keyword and followed by name of the enum.

 The enum is like class, but with limited facilities.

 The enum body contains constants, and other declarations.

 The enum constant declaration contains a constant and its argument in the
parenthesis. EX: RITA(10)
class Math

 The Math class is an important class of java.lang package.


 It has defined number of methods to perform mathematical functions such as
Trigonometric functions, Exponential functions, Rounding off functions, and
other miscellaneous functions.
 The class is defined as Final class (we cannot inherit it) as follow:
Public final class Math extends Object
 All methods in the Math are public and static, hence we can access them without
creating object.
 Write a java program to calculate the area of circle using the Math class.

 Write a java program to calculate the power of the given number raised to a
number.

 Write a java program to determine the greater number of three numbers. (a,b,c)

class Test4
{
public static void main(String arg[]) {
System.out.println("The area of circle with radius 5 is :"+Math.PI*5*5);
System.out.println("The power(8,3) is :"+Math.pow(8,3));
System.out.println("The greater of 17,2,21 is :"+Math.max(Math.max(17,2),21));
}
}

Output:The area of circle with radius 5 is :78.53981633974483


The power(8,3) is :512.0
The greater of 17,2,21 is :21
Wrapper Classes
 A Wrapper class wraps the primitive data and produces its object representation.
 Many classes in java have been designed to work with Object, rather than with
primitive data types.
 In such as context it may be required to convert the primitive data into object.
 For this, the wrapper classes will take primitive data type and provide corresponding
object.
 There are 8 primitive data types such as byte, short, int, long, float, double, char and
Boolean in java.
 These primitive data types can be wrapped using the Byte, Short, Integer, Long, Float,
Double, Character, and Boolean classes.

Constructors of Wrapper classes

Methods of Wrapper classes


Methods for converting Numbers into BinaryString, HexString, OctalString

class Test4
{
public static void main(String arg[])
{
System.out.println("Binry representation of 4 is:"+Integer.toBinaryString(4));
System.out.println("Hex string of 27 is :"+Integer.toHexString(27));
System.out.println("Octal string of 9 is :"+Integer.toOctalString(9));
}
}
C:\Users >java Test4
Binry representation of 4 is:100
Hex string of 27 is :1b
Octal string of 9 is :11
Auto-boxing and Auto-unboxing

 The automatic conversion of the primitive type into its corresponding wrapper
types so that the value may be represented by the reference is called “auto-
boxing”.
 The process of converting the wrapper class objects into primitive type is called
“auto-unboxing”
 Example
Integer x=20; here x is an object (auto-boxing)
int y=x; //here object x is assigned to primitive type variable y (auto-unboxing)

class Test4
{
public static void main(String arg[])
{

Integer io=10; //auto-boxing


System.out.println("The value of io is :"+io.intValue());
int m=io; //auto-unboxing
System.out.println("The value of m is:"+m);
}
}
C:\Users\91970\Documents\JLP\R19>java Test4
The value of io is :10
The value of m is:10

Java.util Classes and Interfaces

 Java.util is an important package in java library.


 It contains classes and interfaces, event models and miscellaneous classes.
 The classes and interfaces are used in number of programs, hence they are very
important.

 For instance, Array, and Vector classes are used for working with arrays and
variable length arrays.
 Along with above classes it also contains Scanner and Formatter classes, the date
and time also part of java.util package.

Some of the classes of java.util


Scanner class

 Java Scanner class is text scanner class that breaks the input into tokens using the
delimiter, which is white space by default.
 Delimiter is not part of the string, it will be at the beginning or at the end.
 The resulting tokens can then be converted into various types of data using the
next() methods.
 The following code allows the user to read input of type int from the keyboard.

Scanner input=new Scanner(System.in);


System.out.println(“Enter Your Roll no:”);
int roll=input.nextInt();

Constructors of Scanner class


 Scanner(File source) - Constructs a new Scanner that produces values scanned from
the specified file.
 Scanner(File source, String charsetName) - Constructs a new Scanner that produces
values scanned from the specified file.
 Scanner(InputStream source) - Constructs a new Scanner that produces values scanned
from the specified input stream.
 Scanner(InputStream source, String charsetName) - Constructs a new Scanner that
produces values scanned from the specified input stream.
 Scanner(Path source) - Constructs a new Scanner that produces values scanned from
the specified path.
Some Methods of Scanner Class

Method Description
nextBoolean() Reads a boolean value from the user
nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads an int value from the user
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user
Returns true if the next token in this scanner's input can be interpreted as an
hasNextInt()
int value in the default radix using the nextInt() method.
Returns true if the next token in this scanner's input can be interpreted as a
hasNextDouble()
double value using the nextDouble() method.
Returns true if the next token in this scanner's input can be interpreted as a
hasNextFloat()
float value using the nextFloat() method.
Formatter Class

 The class Formatter supports the formatting of output for Characters, strings and
numbers.

 We already have used printf() method to avoid string concatenation using the
println() method.

 The Formatter class is used to specify the justification, alignment, formats for
numbers, and strings etc.

 The method format() is used to format the output. The Formatter object is then
passed as an argument to println() method as shown in the following example.

Example Program
Specification of Field Width

 The minimum field can be specified which the output must be formatted using the
filed width.
 This is specified between % and conversion character (Ex: %4d, %6.3f), Here for
integer 4 represents the minimum field width. For floating point number the
integer part contains 6 digits and fractional part contains 3 digits.
 The %n is used to insert \n in the output , and %% is used to append % at the end
of number.

import java.util.*;
class ScanTest
{
public static void main(String arg[])
{
Formatter ft=new Formatter();
int i=12;
double d=123.456788;
String s="Hello Format";
ft.format("%5d %4.3f %20s",i,d,s);
System.out.println(ft);
}}
C:\Users >java ScanTest
12 123.457 Hello Format
Random Class
 The class Random is used to generate random numbers of different types such as
int, double, float, long, and byte.

 The random() method of the Math class also can be used to generate random
numbers from 0.0 to 1.0.

 There are two constructors of Random class.


 Random()- constructs a random number with seed provided by system.
 Random(long seed) –seed number is provided by user.
 Here seed is an integer that sets the starting point for generating number.
 Methods of Random class
 boolean nextBoolean() – generates a random Boolean value.
 byte nextByte() -generates a random byte value.
 int nextInt() -generates a random integer value.
 int nextInt(int n) -generates a random integer value between 0 to n.
 float nextFloat()- generates a random float value.
 Long nextLong() - generates a random long integer value.
 double nextDouble() - generates a random double value.
 Void setSeed(long seed) – sets a seed number in long number.
Example program

import java.util.*;
class TestRandom
{ public static void main(String arg[])
{
Random rand=new Random();
rand.setSeed(10);
System.out.println("The Random long is :"+rand.nextLong());
System.out.println("The Random Integer is :"+rand.nextInt());
System.out.println("The Random double is :"+rand.nextDouble());
System.out.println("The Random boolean is :"+rand.nextBoolean());
System.out.println("Ten random numbers are:");
for(int i=0;i<10;i++)
{
System.out.print(rand.nextInt(10)+"\t");
}}}
C:\Users>java TestRandom
The Random long is :-4972683369271453960
The Random Integer is :1107254586
The Random double is :0.4129126974821382
The Random boolean is : true
Ten random numbers are:
7 8 1 4 3 9 1 8 5 0

Time Package

 The time package provides support for date and time features for developers.
 It contains classes that represent date/time concepts including instants, duration,
date, time, time zones, and periods.
 This date/time framework prior to java 8 are provided by java.util.Date
class, java.util.Calendar class, and java.util.SimpleDateFormatter
class which have some problems as follow:
 These classes are not Thread safe.
 Poor design
 It is difficult to work with different Calendar systems.
 This has led a third party to create ‘Joda-Time’ package.
New Time Package (java.time)
 This was introduced in java8.
 It has four sub packages like java.time.format, java.time.chrono,
java.time.temporal, and java.time.zone.
 There are some terms to understand the time as follow:
 Instant- time since 1st jan 1970
 Time zone – region of the earth where same time standard is followed.
 Time zoneID – It is an identifier of time zone (region)
 Zone offset – it is the difference between time zone and Greenwich time.
Classes of Time package : java.time package contains many classes; the most
commonly used classes are as follows:
 Clock – supports access to instant, time, date
 Duration –deals with time in terms of seconds, and nanoseconds.
 Instant – data time instance sincs 1 st jan 1970
 LocalDate- returns the local date of the system.
 LocalTime- gives the local time of the system.
 LocaDateTime- gives date and time combination of local system.
 ZonedDateTime- returns the date and time of the zone with zone id also.
 ZoneId-gets the Zone Id from the current ZonedDateTime

Class Instant (java.time.Instant)

 This is the core class of new time framework.

 The object return by this class is expressed in terms of seconds since 1 st jan 1970,
which is also called Epoch.

 Any instant before Epoch has a negative value and any instant after Epoch has
positive value.

 The units of instants are always seconds.

 We can convert the seconds into years, day, hours, and minutes as follow:
LocalDateTime t=
LocalDateTime.ofInstant(timestamp,ZoneId.SystemDefault());
 Methods of Instant class
 isAfter (Instant) –Compares two instants, and returns true if the instant is
after given Instant, otherwise false.
 isBefore(Instant) -Compares two instants, and returns true if Instant is before
given instant, Otherwise false.
 plusMinutes(), plusHours() – adds time to instant like hours or minutes.
 minusMinutes(),minusHours() –subtracts the times
 Until() –returns the time left between two instants.
Example Program

import java.time.Instant;
class InstantDemo
{
public static void main(String arg[])
{
Instant now=Instant.now();
System.out.println("The value of present time is :"+now);
Instant before=Instant.now().minusSeconds(500);
System.out.println("The value of before current time is :"+before);
Instant later=Instant.now().plusSeconds(600);
System.out.println("The value of future time is :"+later);
System.out.println("Testing isAfter:"+later.isAfter(now));
}

Output

C:\Users >java InstantDemo


The value of present time is :2023-11-03T14:40:59.444996Z
The value of before current time is :2023-11-03T14:32:39.738670Z
The value of future time is :2023-11-03T14:50:59.739387Z
Testing isAfter:true
Formatting for Date
 In many countries , different formats are followed for formatting date/time data.
 In some countries Calendar system itself is different from what most of the
countries follow.
 In order to fulfil these requirements java 8 has introduced new class for
formatting, printing, and parsing date/time objects.
 The new class is DateTimeFormatter
 The class provides the following Three ways to achieve desired results.
 By using the predefined constants.
 By using the patterns defined by programmer.
 By using the localized format.
Predefined constants with different styles
Standard formatter Description

BASIC_ISO_DATE 20150126->means 2015 Jan 26

ISO_DATE 2015-08-22
ISO_DATE_TIME 2015-08-22 11:20:40

ISO_INSTANT Ex:2015-10-03T10:15:24
ISO_LOCAL_DATE 2015-11-20

import java.time.format.DateTimeFormatter;
import java.time.LocalDateTime;
class FormatDateDemo
{ public static void main(String arg[])
{
LocalDateTime t=LocalDateTime.now();
System.out.println("Local Date Time is:"+t);
System.out.println("User format Format:"
+t.format(DateTimeFormatter.ofPattern("dd-MMM-
yyyy hh:mm:ss")));
System.out.println("User format 2:"
+t.format(DateTimeFormatter.ofPattern("yyyy-
MMM-dd hh:mm:ss")));
}
}

C:\Users >java FormatDateDemo


Local Date Time is:2023-11-03T14:45:27.284906
User format Format:03-Nov-2023 02:45:27
User format 2:2023-Nov-03 02:45:27
Temporal Adjusters Class

 The methods of this class are useful to determine first day of month, last day of year
among others.

 This class has the following methods:


 firstDayOfMonth()
 lastDayOfMonth()
 firstDayOfYear()
 lastDayOfYear()
 firstDayOfWeek()
 lastDayOfWeek()

import java.time.*;
import java.time.temporal.TemporalAdjusters;
class TemporalTest
{ public static void main(String arg[]) {
LocalDate date1=LocalDate.of(2015,Month.NOVEMBER,20);
DayOfWeek dw=date1.getDayOfWeek();
System.out.println("The day of the week :"+dw);
System.out.println("The last day of November is:"
+date1.with(TemporalAdjusters.lastDayOfMonth()));
}
}

C:\Users >java TemporalTest


The day of the week :FRIDAY
The first day of November is:2023-11-30
Exception Handling

Exception: The error raised when the program is in execution is called Exception or Runtime
Error. This is raised due the mistake made by the user or system.
An exception is an unexpected event that occurs during program execution. It affects the flow of
the program instructions which can cause the program to terminate abnormally.
 Some of the exceptions are as follow:
🞑 Giving negative number as array size.
🞑 Giving negative as argument for method to find square root.
🞑 Opening a file that does not existing.
🞑 When the file is not found.
🞑 Dividing a number by zero
In Java, an exception is an object of a relevant exception class.
 When an error occurs in a method, it throws out an exception object that contains the
information about where the error occurred and the type of error.
 The error (exception) object is given to the runtime system, which searches for the
appropriate code that can handle the exception.
 The exception handling code is called exception handler.
 Exception handling is a mechanism that is used to handle Runtime Errors such as divide by
zero error,classNotFound and IO.
This ensures that the normal flow of application program is not disrupted and program
execution proceeds smoothly.
 The exception handling code handles only the type of exception that is specified for it to
handle.
 The appropriate code is the one whose specified type matches the type of exception thrown
by the method.
 If the runtime system finds such a handler, it passes on the exception object to the handler.
 If an appropriate handler is not found, the program terminates.
The method that generates an exception may itself provide a code to deal with it.
Exception handling is managed by Java via five keywords:
 try
 catch
 throw
 throws
 finally.
Working Exception handling Techniques:
1. Briefly, here is how they work. Program statements that you want to
monitor forexceptions are placed within a try block.
2. If an exception occurs within the try block, it is thrown. Your code can
catch thisexception (using catch) and handle it in some rational manner.
3. System-generated exceptions are automatically thrown by the Java run-
time system.To manually throw an exception, use the keyword throw.
4. Any exception that is thrown out of a method must be specified as such by a throws
clause.
5. Any code that absolutely must be executed after a try block completes is put in a
finally block.
Syntax:
try
{

}
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb)
{
// exception handler for ExceptionType2
}
// ...
finally
{

// block of code to be executed after try block ends

}
The try and catch blocks

The try-catch block is used to handle exceptions in Java.


The try block:
🞑 The program code that is most likely to generate exceptions is kept in the try block,
which is followed by the catch block to handle the exception.
🞑 In normal execution, the statements are executed and if there are no exceptions, the
program flow goes to the code line after the catch blocks.
🞑 However, if there is an exception, an exception object is thrown from the try block. Its
data members keep the information about the type of exception thrown.
🞑 The program flow comes out of the try block and searches for an appropriate catch
block with the same type as its argument.
The catch block:
🞑 A catch block is meant to catch the exception if the type of its argument matches with
the type of exception thrown.

🞑 If the type of exception does not match the type of the first catch block, the program
flow checks the other catch blocks one by one.

🞑 If the type of a catch block matches, its statements are executed.

🞑 If none matches, the program flow records the type of exception, executes the finally
block, and terminates the program.

Here's the syntax of try...catch block:

try {
// code
}
catch(Exception e) {
// code
}

Here, we have placed the code that might generate an exception inside the try block. Every try
block is followed by a catch block.

When an exception occurs, it is caught by the catch block. The catch block cannot be used
without the try block. There may be more than one catch blocks.

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

try {

// code that generate exception


int x = 5 / 0;
System.out.println("Rest of code in try block");
}
catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}
}
}
Output: ArithmeticException => / by zero

The finallyblock:

 This is the block of statements that is always executed even when there is an
exceptional condition, which may or may not have been caught or dealt with.
 Thus, finally block can be used as a tool for the clean up operations and for
recovering the memory resources.
 For this, the resources should be closed in the finally block.
import java.util.*;
class ThrowExcep
{
int a,b,c;
void read() throws InputMismatchException,ArithmeticException
{
Scanner in=new Scanner(System.in);
System.out.println("Enter a and b values:");
a=in.nextInt();
b=in.nextInt();
c=a/b;
System.out.println("Division is:"+c);
}
}
class ThrowTest
{
public static void main(String args[])
{
ThrowExcep t=new ThrowExcep();
try
{
t.read();
}
Catch (Exception e)
{
System.out.println("Exception is:"+e);
}
finally
{
System.out.println("End of the main program");
} }}
Output1: Enter a and b values:
4
0
Exception is:java.lang.ArithmeticException: / by zero
End of the main program
Output2: Enter a and b values:
4b
Exception is:java.util.InputMismatchException
End of the main program
Hierarchy of Standard Exception Classes

 In Java, exceptions are instances of classes derived from the class Throwable which in turn
is derived from class Object.
 Whenever an exception is thrown, it implies that an object is thrown.
 Only objects belonging to class that is derived from class Throwable can be thrown as
exceptions.
 Some of the examples of Error including OutOfMemoryError occurs when the JVM runs
out of memory and StackOverflowError occurs when the stack overflows.

 Exception class represents exceptions that are mainly caused by the application itself.

 It is not possible to recover from an error using try–catch blocks.

 The only option available is to terminate the execution of the program and recover from
exceptions using either the try–catch block or throwing an exception.

 The exception class has several subclasses that deal with the exceptions that are caught and
dealt with by the user’s program.
 The Error class includes such errors over which a programmer has less control.

 A programmer cannot do anything about these errors except to get the error message and
check the program code.

 A programmer can have control over the exceptions (errors) defined by several subclasses
of class Exception.

 The subclasses of Exception class are broadly subdivided into two Categories:
🞑 Unchecked exceptions
These are subclasses of class RuntimeException, derived from Exception class. For
these exceptions, the compiler does not check whether the method that throws these
exceptions has provided any exception handler code or not.

🞑 Checked exceptions
These are direct subclasses of the Exception class and are not subclasses of the class
RuntimeException. These are called so because the compiler ensures (checks) that the
methods that throw checked exceptions deal with them. Ex; IOException in main
method.
 This can be done in two ways:
1. The method provides the exception handler in the form of appropriate try–catch blocks.
2. The method may simply declare the list of exceptions that the method may throw with
throws clause in the header of the method.
🞑In this case, the method need not provide any exception handler.
🞑It is the responsibility of the caller to handle the exception in its code.
 Note: If a method does not follow either of the aforementioned ways, the compilation will
result in an error.

Throwable class: All exception types are subclasses of the built-in class Throwable. Thus,
Throwable is at the top of the exception class hierarchy.The Throwable has several methods. The
three commonly usedmethods for getting information about the exceptions are as follow:

Throws:
If a method can cause one or more checked exceptions directly or indirectly by calling other
methods and throw exceptions and does not handle with them, it must declare the list of
exceptions it can throw by using the throws clause.
 By doing this, the caller of the method can ensure that appropriate arrangements are made to
handle with the exceptions. The caller may be other method or JVM.
 For this, keep the method in a try block, and provide suitable catch blocks.
 The program will not compile if this is not done.
 The throws clause comprises the keyword throws followed by the list of exceptions that the
method is likely to throw separated by commas.
 The method declaration with throws clause is
type methodname(type parameters) throws list-of-Exceptions
{ /* Body of Method*/ }
Throw keyword
 The throw keyword in Java is used to explicitly throw an exception from a method or any
block of code.

 We can throw either checked or unchecked exception.

 The throw keyword is mainly used to throw custom exceptions or user defined exceptions.
 Syntax: throw Instance;
 Example: throw new ArithmeticException("/ by zero");

Example program to illustrate throw keyword

Uncaught exceptions
 Whenever an exception is thrown it must be handle by the handler.
 If no catch block is provided or an exception is not caught, it is handled by the JVM
by default which usually terminates the program execution and display an error
message at the end.
Note: After try block, the finally block will be executed if catch block is not present.
try {
//statements
}
finally { }
Finalize() in Exception Handling

 The finalize() method is called by garbage collector thread, and thereby memory
allocated to the object is reclaimed.

 Any exception thrown by finalize method is ignored by the garbage collector thread
and it is not logged into the log files.

 The syntax for using finalize() method is given as follows:


Multiple Catch Clauses
 Often the programs throw more than one type of exception.

 The programmer has to provide a catch block for each type of exception.

 At times, it is quite a clumsy task often not liked by programmers.

 One way to reduce this use hierarchy of classes and super class as argument of catch
block, so that the number of exceptions are caught.

 However it is not suitable because it hides the information about what really went
wrong.

 Since Java 7, a modification has been done in the language so that one catch block
can catch more than one type of exception.

 The exception classes are connected by Boolean operator OR.


Class Throwable

 The class is declared as


public class Throwable extends Object implements serializable

 The class Throwable is super class to all the Error and Exception classes.
 The program code can throw only objects of this class or objects of its subclasses.
 Only the object of Throwable class or its subclasses can be the arguments of catch
clause.
 It would be a bad programming practice to throw Throwable or make Throwable as
argument of catch blocks because it will hide desirable information.
Constructors of class Throwable

Methods of class Throwable

The Throwable class has several methods. Since the Throwable is the super class, all the
Sub classes can access these methods. Some of the methods are as follows:
Unchecked Exceptions
 It is not checked by the compiler whether the programmer has handled them or not.

 The unchecked exception classes are subclasses of class RuntimeException, which


is further a subclass of class Exception.

 The runtime exceptions are not checked by the compiler.

 These exceptions form a subgroup of classes that are subclasses of class Exception.
Unchecked subclasses of RuntimeException

Checked Exceptions

 These are the exceptions that are checked by the compiler and these are also called
compiled time exceptions.

 These exceptions cannot be ignored at the time compilation.

 The programmer has to handle these exceptions, if not handle these exceptions will
give compilation errors.
try-with-resources

 Generally, the resources such as file, data bases, or Internet connections that are opened in
try block are closed in finally block, which is always executed.This makes
a sure-shot (guaranteed) method for recovery of sources and memory.
 It is observed that programmers who are not skillful often forget to close files, and data
bases what they have opened when their work is over.
 In order to redress the problem, Java 7 has added AutoCloseable interface along with it
another try block called “try-with_resources”.
 This AutoCloseable interface has one method called close() which will be automatically
invoked by the sources that implement the interface and are managed by try-with-sources.
Catching Subclass Exception

 A programmer may define a method in super class.

 When this method is overridden in the sub class with exception handling, then following
points must be considered.
🞑 If the super class method does not declare any exception, then subclass overridden
method cannot declare checked exceptions, but it can declare unchecked exceptions.

🞑 This can be understood with following example

Custom Exception or user-defined exception:

Java user-defined exception is a custom exception created by user and throws that exception
using a keyword ‘throw’. It is done by extending a class ‘Exception’. Java allows us to create our
own exception class, which provides own exception class implementation. Such exceptions are
called user-defined exceptions or custom exceptions.
To implement a user-defined exception in Java, follow these steps:

 Create a custom exception class that extends the base exception class
(java.lang.Exception).
 Define the constructor for the custom exception class. The constructor can accept
parameters to provide more information about the error.
 Override the toString() method to provide a custom error message.
 Use the "throw" keyword to throw an instance of the custom exception when the error
condition occurs.
 Use a "try-catch" block to catch the exception and handle it appropriately.

import java.util.*;
//user defined exception
class NegativeExp extends Exception
{
//constructor
NegativeExp(String msg)
{
super(msg);
}
}
Nested try and catch blocks

 In nested try-catch blocks, one try catch can be placed within another try’s body.

 Nested try-block is used where a part of the body may cause one error, and the entire part
may cause another error. In such cases exception handlers are nested.

 If a try block does not have a catch handler for a particular exception, the next try block’s
catch handlers are inspected for a match.

 If no catch block matches, then the Java runtime system handles the exception.
Syntax
try
{ //main try block
//Statements here try{//try block 1
//statements here
try{ //try block 2
//statements here
} catch(Exception e1)
{
//Statements of Innermost catch block
}
} catch(Exception e2)
{//Statements of Middle catch block
}
}
catch(Exception e)
{
//Outer most catch block
}
Rethrowing Exception

 An exception may be thrown and caught and also partly dealt within a catch block, and
then, rethrown.
 In many cases, the exception has to be fully dealt within another catch block, and throw the
same exception again or throw another exception from within the catch block.
 When an exception is rethrown and handled by the catch block,
🞑 The compiler verifies that the type of re-thrown exception is meeting the conditions
that the try block is able to throw
🞑 and there are no other preceding catch blocks that can handle it.

You might also like