Unit - 4
4.1 Packages and Java Library:
4.1.1 Introduction,
4.1.2 Defining Package,
4.1.3 Importing Packages and Classes into Programs,
4.1.4 Java.lang Package and its Classes,
4.1.5 class Math,
4.1.6 Wrapper Classes,
4.1.7 Java util Classes and Interfaces,
4.1.8 Time Package,
4.1.9 Class Instant (java.time.Instant).
4.2 Exception Handling:
4.2.1 Introduction,
4.2.2 Keywords throws and throw, try, catch, and finally
Blocks,
4.2.3 Multiple Catch Clauses,
4.2.4 Class Throwable,
4.2.5 Unchecked Exceptions,
4.2.6 Checked Exceptions,
4.2.7 Catching Subclass Exception,
4.2.8 Custom Exceptions
4.1 Packages
4.1 Packages
Packages are considered as folders in the directory. They are used to store the classes,
interfaces, and sub-packages of similar types. They are the main part of the encapsulation
process as they help in encapsulating the data of the same type.
We generally use the package keyword to make a package.
There are two types of packages:
1. Built-in packages: The packages which are already present in java are known as built-in
packages. For example, util, io, lang, etc.
Program:
import java.util.Scanner;
class Addition
{
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
int a = s.nextInt();
int b = s.nextInt();
int c = a+b;
System.out.println(“Addition of ” + a+ “and ”+b+” is ” +c);
}
}
2. User-defined packages: The packages which are made by the users are known as user-
defined packages.
Program:
package coders;
class UserDefined
{
public void getMessage()
{
System.out.println(“Hello Guys!”);
}
}
Accessing package from another package
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1)packageName.*
When we use this method, then all the classes and interfaces in that package will be accessible
but not subpackages.
The import keyword is used to make the classes and interface of another package accessible to
the current package.
Program:
package programmers;
import coders.*;
class Message
{
public void setMessage()
{
System.out.println(“Welcome to Java Programming”);
}
public static void main(String args[])
{
Message m = new Message();
m.setMessage();
UserDefined d = new UserDefined();
d.getMessage();
}
}
Comment for Compilation and execution
javac -d filedirectory.filename
java packagename.classname
2)Using packagename.classname
When we use this method then only a particular class of that package gets imported.
Program:
package programmers;
import coders.UserDefined;
class Message
{
public void setMessage()
{
System.out.println(“Welcome to Java Programming”);
}
public static void main(String args[])
{
Message m = new Message();
m.setMessage();
UserDefined d = new UserDefined();
d.getMessage();
}
}
3) Using fully qualified name
If we use this method then all the declared classes of that package get imported. In this method,
there is no need to write import because we can access its classes by using
packageName.className inside the class at creation of the object. It is generally used when
the two packages have classes with the same name.
Program:
package programmers;
class Message
{
public void setMessage()
{
System.out.println(“Welcome to Java Programming”);
}
public static void main(String args[])
{
Message m = new Message();
m.setMessage();
coders.UserDefined d = new coders.UserDefined();
d.getMessage();
}
}
4.1.4 Java.lang Package and its Classes
The lang package in Java provides classes and interfaces that are fundamental to the design of
the Java programming language. It is a built-in package provided by the JDK (Java
Development Kit). The classes and interfaces of the lang package are found under the
path java.lang.
java.lang package is a default package in Java, which means that it is automatically imported
into all Java programs. As a result, you can use the classes and interfaces in this package
without explicitly importing them.
The lang packages contain classes such as Math, Thread, Exception and also wrapper classes
like Int, Long, Double, Boolean etc.,
Classes of Lang Package in Java
Boolean
The Boolean class wraps the value of a boolean primitive type in an object. It contains a single
attribute value of type boolean.
Byte
The Byte class wraps a value of primitive type byte in an object. An object of
type Byte contains a single field whose type is byte.
Character
The Character class wraps a value of the primitive type char in an object. An object of
class Character contains a single field whose type is char.
Double
The Double class wraps a value of the primitive type double in an object. An object of
type Double contains a single field whose type is double.
Class
The instance of the Class class represents the classes and interfaces in a running java
application. Class has no public constructor. Instead their objects are constructed automatically
by the Java Virtual Machine.
Double
The Double class wraps a value of the primitive type double in an object. An object of
type Double contains a single field whose type is double.
Exception
The Exception class and its subclasses are a form of Throwable that indicates conditions that a
reasonable application might want to catch.
Float
The Float class wraps a value of primitive type float in an object. An object of
type Float contains a single field whose type is float.
Integer
The Integer class wraps a value of the primitive type int in an object. An object of
type Integer contains a single field whose type is int.
Long
The Long class wraps a value of the primitive type long in an object. An object of
type Long contains a single field whose type is long.
Math
The Math class contains methods for performing basic numeric operations such as the
elementary exponential, logarithm, square root, and trigonometric functions.
Object
The Object is the root of the class hierarchy. Every class has Object as a superclass.
String
The String class represents character strings. The values in the String class are constant and
cannot be changed after they are created.
StringBuilder
The StringBuilder class contains a mutable sequence of characters. The StringBuilder class is
an alternative to the String class as its values are mutable.
System
The System class contains several useful class fields and methods. It contains only a private
constructor and cannot be instantiated.
Thread
The Thread class is used to create and run threads in a Java program. It is very useful when a
Java program has to be run in a multi-threaded environment.
Program:
public class MainClass
{
public static void main(String[] args)
{
Boolean bool = Boolean.valueOf(false);
Byte by = Byte.valueOf((byte)1);
Character character = Character.valueOf('a');
Double doub = Double.valueOf(1.25);
Float fl = Float.valueOf(1.1f);
Integer integer = Integer.valueOf(10);
Long l = Long.valueOf(1000000L);
System.out.println("Boolean: " + bool);
System.out.println("Byte: " + by);
System.out.println("Character: " + character);
System.out.println("Double: " + doub);
System.out.println("Float: " + fl);
System.out.println("Integer: " + integer);
System.out.println("Long: " + l);
}
}
Output:
4.1.5 Class Math
The Java Math class is part of the java.lang package, which means it is automatically
available to all Java programs.
It is designed to facilitate numerical computations by providing methods for common
mathematical functions, such as trigonometric, logarithmic, exponential, and rounding
operations.
Since the Math class is static, we don’t need to create an instance of it; instead, you can
directly access its methods using the class name.
1. Basic Mathematical Methods
The Math class provides many methods that one can easily delve into and apply. All the basic
functions of Math are listed in this table.
Method Description
The Absolute value of the given value will be
Math.abs()
returned.
Math.max() It returns the larger of two possible values.
Its purpose is to return the smaller of two
Math.min()
values.
It is used to round decimal numbers to the
Math.round()
nearest whole number.
Math.sqrt() It calculates the square root of a number.
Math.cbrt() It is used to return a number’s cube root.
It returns the value of the first argument raised
Math.pow()
to the power of the second.
Math.signum() It determines the sign of a given value.
Method Description
Its purpose is to find the smallest integer value
Math.ceil() greater than or equal to the argument or
mathematical integer.
It is used to determine the Absolute value of
Math.copySign() the first argument as well as the sign specified
in the second argument.
It is used to return the floating-point number
Math.nextAfter() next to the first argument in the direction of
the second.
It is used to find the largest integer value that
is less than or equal to the argument and is
Math.floor()
equal to the mathematical integer of a double
value.
It returns a double value with a positive sign,
Math.random()
greater than or equal to 0.0 and less than 1.0.
It is used to return the unbiased exponent used
Math.getExponent()
in the representation of a value.
2. Basic Arithmetic Functions
The Math class includes methods to perform basic arithmetic operations like addition,
subtraction, multiplication, and division:
double additionResult = Math.addExact(a, b);
double subtractionResult = Math.subtractExact(a, b);
double multiplicationResult = Math.multiplyExact(a, b);
3. Power and Exponential Functions
You can calculate the power of a number and compute exponentials using the following
methods:
double powerResult = Math.pow(base, exponent);
double exponentialResult = Math.exp(x);
4. Square Root and Cube Root
To find the square root or cube root of a number, use these methods:
double squareRootResult = Math.sqrt(number);
double cubeRootResult = Math.cbrt(number);
5. Trigonometric Functions
The Java Math class offers various trigonometric methods such as sine, cosine, tangent, and
their inverses (arcsine, arccosine, and arctangent). Here a complete description of all
functions involved.
Method Description
It is used to return the trigonometric Sine value of a Given double
Math.sin()
value.
Method Description
It is used to return the trigonometric Cosine value of a Given double
Math.cos()
value.
It is used to return the trigonometric Tangent value of a Given double
Math.tan()
value.
It is used to return the trigonometric Arc Sine value of a Given double
Math.asin()
value
It is used to return the trigonometric Arc Cosine value of a Given
Math.acos()
double value.
It is used to return the trigonometric Arc Tangent value of a Given
Math.atan()
double value.
double sineResult = Math.sin(angleInRadians);
double cosineResult = Math.cos(angleInRadians);
double tangentResult = Math.tan(angleInRadians);
double arcSineResult = Math.asin(value);
double arcCosineResult = Math.acos(value);
double arcTangentResult = Math.atan(value);
Program:
public class MathClass
{
public static void main(String[] args)
{
double x = -8;
double y = 4;
double y = 4.2;
System.out.println("Maximum number of x and y is: " +Math.max(x, y
));
System.out.println("Square root of y is: " + Math.sqrt(y));
System.out.println("Power of x and y is: " + Math.pow(x, y));
System.out.println("Logarithm of x is: " + Math.log(x));
System.out.println("Logarithm of y is: " + Math.log(y));
System.out.println("Absolute value of x is: " +Math.abs(x));
System.out.println("Ceil value of z is: " +Math.ceil(z));
System.out.println("Floor value of z is: " +Math.floor(z));
}
}
Output:
Maximun number of x and y is: 8.0
Square root of y is: 2
Power of x and y is: 4096
Logarithm of x is: 2.0794415
Logarithm of y is: 0.69314713
Absolute value of x is: 8.0
Ceil value of z is: 5.0
Floor value of z is: 4.0
4.1.6 Wrapper classes
Java is an impure object-oriented programming language because it supports primitive
data type.
Primitive data types are not treated as objects in java.
Java is an object-oriented programming language, we need to deal with objects many
times like in Collections, Serialization, Synchronization, etc. so by using wrapper
classes we can achieve fully object orientation in java.
The wrapper class in Java are used to convert primitive data types into object and
object into primitive data types.
The classes in java.util package handles only objects and hence wrapper classes help
in this case.
Following is a list of the eight wrapper classes
Primitive Type Wrapper Class
char Character
short Short
long Long
double Double
boolean Boolean
byte Byte
int Integer
float Float
Autoboxing
Autoboxing is when the Java compiler automatically converts the primitive data types to the
object of their corresponding wrapper classes. For example, converting an int to Integer,
a double to Double, etc.
Syntax:
datatype variable_name = value;
WrapperClass_name reference_variable = WrapperClass_name.valueOf(variable_name);
//Explict conversion of primitive to wrapper class.
WrapperClass_name reference_variable = variable_name;
//implicit conversion of primitive to wrapper class.
Example:
int a = 23;
Integer i = Integer.valueOf(a); //Explicit Conversation
Integer ii = a; // Implicit Conversation
Unboxing
The automatic conversion of wrapper type into its corresponding primitive type is known as
unboxing. It is the reverse process of autoboxing. For example, converting an Integer to int,
Double to double, etc.
Syntax:
WrapperClass_name reference_variable = new WrapperClass_name(value);
datatype variable_name = reference_variable.intValue();
//Explict conversion of primitive to wrapper class.
datatype variable_name = reference_variable;
//implicit conversion of Wrapper to Primitive
Example:
Integer i = new Integer(23);
int a = i.intValue();
int aa = i;
Program:
class WrapperClass
{
public static void main(String args[])
{
byte b=2;
short s=42;
int i=34;
long l=40;
float f=75.0F;
double d=20.0;
char c='n';
boolean bl=false;
//Autoboxing : Primitive to Objects
Byte by=b;
Short sh=s;
Integer in=i;
Long lon=l;
Float fl=f;
Double doub=d;
Character ch=c;
Boolean boo=b2;
System.out.println("Printing object values");
System.out.println("Byte object: "+by);
System.out.println("Integer object: "+in);
System.out.println("Short object: "+sh);
System.out.println("Long object: "+lon);
System.out.println("Double object: "+doub);
System.out.println("Float object: "+fl);
System.out.println("Boolean object: "+boo);
System.out.println("Character object: "+ch);
//Unboxing : Converting Objects to Primitive types
byte bytevalue=by;
short shortvalue=sh;
int intvalue=in;
long longvalue=lon;
float floatvalue=fl;
double doublevalue=doub;
char charvalue=ch;
boolean boolvalue=boo;
System.out.println("Printing primitive values");
System.out.println("byte value: "+bytevalue);
System.out.println("int value: "+intvalue);
System.out.println("short value: "+shortvalue);
System.out.println("long value: "+longvalue);
System.out.println("double value: "+doublevalue);
System.out.println("float value: "+floatvalue);
System.out.println("boolean value: "+boolvalue);
System.out.println("char value: "+charvalue);
}
}
Advantage of Wrapper class: The program becomes pure object oriented.
Disadvantage of Wrapper class: Execution speed decreases.
Advantage of Primitive data type: Faster in execution.
Disadvantage of Primitive data type: The program becomes impure object oriented.
4.1.7 Java util Classes and Interfaces
The java.util package in Java is a built-in package that contains various utility classes and
interfaces. It provides basic functionality for commonly occurring use cases. It contains Java's
collections framework, date and time utilities, string-tokenizer, event-model utilities, etc.
Collections Framework in Java is a special part of the java.util package that can be used to
represent and manipulate collections.
java.util Package Interfaces
Interface Description
Collections Root interface for the Collections API
Comparator Provides sorting logic
Deque Implements Deque data structure
Enumeration Produces enumeration objects
Iterator Provides iteration logic
List Implements an ordered collection (Sequence)
Implements Map data structure (key-value
Map
pairs)
Queue Implements Queue data structure
Produces a collection that contains no
Set
duplicate elements
Produces a set that remembers the total
SortedSet
ordering
java.util packages classes
Class Description
Provides methods to represent and manage
Collections
collections
Formatter An interpreter for format strings
Scanner Text scanner used to take user inputs
Arrays Provides methods for array manipulation
LinkedList Implements Doubly-linked list data structure
HashMap Implements Map data structure using Hash tables
TreeMap Implements Red-Black tree data structure
Stack Implements last-in-first-out (LIFO) data structure
PriorityQueue Implements unbounded priority queue data structure
Date Represents a specific instance of time
Calendar Provides methods to manipulate calendar fields
Used to generate a stream of pseudorandom
Random
numbers.
StringTokenizer Used to break a string into tokens
Timer, TimerTask Used by threads to schedule tasks
Represents an immutable universally unique
UUID
identifier
4.1.8 Time Package
The time package is a standard library package that provides functionalities for working with
time-related operations in programs. It includes tools for representing time values, calculating
durations, manipulating time, formatting time values, handling time zones, and scheduling
time-based events. The time package is essential for tasks such as measuring time intervals,
scheduling tasks, parsing and formatting time strings, and performing various time-related
calculations. It enables developers to handle time-related tasks efficiently and accurately
within their applications.
Java Clock Class
Provides access to the current instant, date and time using a time-zone.
LocalDate Class
A LocalDate represents a year-month-day in the ISO calendar and is useful for representing
a date without a time. We might use a LocalDate to track a significant event, such as a birth
date or wedding date.
LocalDateTime Class
The LocalDateTime is used to represent a combination of date and time.
Duration Class
A Duration is most suitable in situations that measure machine-based time, such as code that
uses an Instant object. A Duration object is measured in seconds or nanoseconds and does
not use date-based constructs such as years, months, and days, though the class provides
methods that convert to days, hours, and minutes.
Instant Class
One of the core classes of the Date-Time API is the Instant class, which represents the start
of a nanosecond on the timeline. This class is used for generating a time stamp to represent
machine time. Java Instant class is used to represent the specific moment on the timeline.
Period Class
The Period class represents a quantity of time in terms of years, months and days. A Period
uses date-based values (years, months, days).
Year Class
The Year class is an immutable date-time object that represents a year. Any field that can be
derived from a year can be obtained.
MonthDay Class
Represents a combination of a month and day, without a year.
Program:
import java.time.Clock;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.MonthDay;
import java.time.Year;
class TimePackageClass
{
public static void main(String args[])
{
Clock c = Clock.system.DefaultZone();
System.out.println(“Current Time: ” + c.instant());
Duration d = Duration.ofSeconds(60);
System.out.println(“Duration: ” + d);
LocalDate ld = LocalDate.now();
System.out.println(“Current date: ” + ld);
LocalDateTime ldt = LocalDateTime.now();
System.out.println(“Current date-time: ” + ldt);
LocalTime lt = LocalTime.now();
System.out.println(“Current time: ” + lt);
MonthDay md = MonthDay.now();
System.out.println(“Current month-day: ” + md);
Year y = Year.now();
System.out.println(“Current year: ” + y);
}
}
4.1.9 Class Instant (java.time.Instant)
One of the core classes of the Date-Time API is the Instant class, which represents the start
of a nanosecond on the timeline. This class is used for generating a time stamp to represent
machine time. Java Instant class is used to represent the specific moment on the time line. It
inherits the Object class and implements the Comparable interface.
Program:
import java.time.Instant;
public class InstantClass
{
public static void main(String[] args)
{
Instant inst = Instant.parse("2017-02-03T10:37:30.00Z");
System.out.println(inst);
Instant instant = Instant.now();
System.out.println(instant);
ins = inst.minus(Duration.ofDays(125));
System.out.println(ins);
inss = inst.plus(Duration.ofDays(125));
System.out.println(inss);
}
}
Advantages:
Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
Java package provides access protection or security by not allowing unauthorized
access. The private or protected variables, classes can not be accessed outside the same
package.
Java package removes naming collision.
4.2 Exception Handling
4.2.1 Introduction
Exception Handling in Java is one of the effective means to handle runtime errors so that the
regular flow of the application can be preserved. Java Exception Handling is a mechanism to
handle runtime errors such as ClassNotFoundException, IOException, SQLException,
RemoteException, etc.
Exception is an unwanted or unexpected event, which occurs during the execution of a
program, i.e. at run time, that disrupts the normal flow of the program’s 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.
4.2.2 Keywords throws and throw, try, catch, and finally Blocks
When an exception occurs the runtime system checked for a special code inside the program
if it is didn’t find any exception handler code the control was given to default exception handler
then the program was abruptly terminated without execution of the remaining lines. To avoid
this abrupt termination, we can use try catch block in Java.
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. The finally block follows the try-catch block.
Program:
class TryCatch
{
public static void main(String args[])
{
try
{
System.out.println("Inside the try block");
int data=25/0;
System.out.println(data);
}
catch(Exception e)
{
System.out.println(“Invalid input”);
//System.out.println(e); /*Inside the try block
java.lang.ArithmeticException: / by zero */
//e.printStackTrace(); /* Inside the try block
Exception in thread "main" java.lang.ArithmeticException: / by zero at
TryCatch.main(TryCatch.java:8) */
}
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
4.2.3 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, to perform different tasks at the occurrence of different
exceptions, use java multi-catch block.
If one exception occurs then only one catch block is executed.
All catch blocks must be ordered from most specific to general, i.e. catch for
ArithmeticException must come before catch for Exception.
Program:
import java.util.Scanner;
public class MultipleCatch
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
try
{
int a = s.nextInt();
int b = s.nextInt();
int c = a/b;
int ar[]=new int[a];
int index = s.nextInt();
ar[index] =s.nextInt();
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs
");
}
catch(NegativeArraySizeException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs
");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
Now whenever the exception object is generated it checks for all the exception handler
or all the catch blocks and the respective message is displayed.
If by chance an exception occurred but it doesn’t belong to any of the above mention
exceptions then it goes to general exception handler.
Starting from Java 7.0, it is possible for a single catch block to catch multiple exceptions
by separating each with | (pipe symbol) in the catch block.
Catching multiple exceptions in a single catch block reduces code duplication and
increases efficiency. The bytecode generated while compiling this program will be smaller
than the program having multiple catch blocks as there is no code redundancy.
Program:
import java.util.Scanner;
public class MultipleCatch
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
try
{
int a = s.nextInt();
int b = s.nextInt();
int c = a/b;
int ar[]=new int[a];
int index = s.nextInt();
ar[index] =s.nextInt();
}
catch(ArithmeticException |ArrayIndexOutOfBoundsException |
NegativeArraySizeException | Exception e)
{
System.out.println("Exception occurs "+ e);
}
}
}
Propagation of an Exception object
Whenever there are multiple methods and if within a method an exception gets
generated it handles it to the Run time System.
The Run time System checks if there is any try-catch block to handle the exception.
If there no try-catch block to handle the exception, then the Exception object does not
directly goes to the default exception handler instead it gets propagated below the
stack.
If the caller of the method also does not handle the exception with try-catch then it
propagates below the stack and this continues until any of the method handles the
exception.
If none of the methods handles the exception then it reaches the Default Exception
handler and Abrupt Termination happens.
Once an exception is caught it does not gets propagate down to the caller methods and
normal termination of the program happens.
Program:
import java.util.Scanner;
class Demo1
{
void fun1()
{
System.out.println(“Connection4 is established”);
Scanner s = new Scanner(System.in);
int a = s.nextInt();
int b = s.nextInt();
int c = a/b;
System.out.println(c);
System.out.println(“Connection4 is terminated”);
}
}
class Demo2
{
void fun2()
{
System.out.println(“Connection3 is established”);
Demo1 d1 = new demo1();
d1.fun1()
System.out.println(“Connection3 is terminated”);
}
}
class Demo3
{
void fun3()
{
System.out.println(“Connection2 is established”);
Demo2 d2 = new demo2();
d2.fun2()
System.out.println(“Connection2 is terminated”);
}
}
class Demo
{
public static void main(String args[])
{
System.out.println(“Connection1 is established”);
Demo3 d3 = new demo3();
d3.fun3()
System.out.println(“Connection1 is terminated”);
}
}
Let us make use of Stack segment to understand the above program.
Below code using Exception mechanism handles for one of the method
Program:
import java.util.Scanner;
class Demo1
{
void fun1()
{
System.out.println(“Connection4 is established”);
Scanner s = new Scanner(System.in);
try
{
int a = s.nextInt();
int b = s.nextInt();
int c = a/b;
System.out.println(c);
}
catch(Exception e)
{
System.out.println(“Some Problem Occured”);
}
System.out.println(“Connection4 is terminated”);
}
}
class Demo2
{
void fun2()
{
System.out.println(“Connection3 is established”);
Demo1 d1 = new demo1();
d1.fun1()
System.out.println(“Connection3 is terminated”);
}
}
class Demo3
{
void fun3()
{
System.out.println(“Connection2 is established”);
Demo2 d2 = new demo2();
d2.fun2()
System.out.println(“Connection2 is terminated”);
}
}
class Demo
{
public static void main(String args[])
{
System.out.println(“Connection1 is established”);
Demo3 d3 = new demo3();
d3.fun3()
System.out.println(“Connection1 is terminated”);
}
}
Let us make use of Stack segment to understand the above program.
Throw Keyword:
The Java throw keyword is used to throw an exception explicitly.
We specify the exception object which is to be thrown. The Exception has some
message with it that provides the error description.
We can throw either checked or unchecked exceptions in Java by throw keyword. It is
mainly used to throw a custom exception.
The disadvantage of throw keyword is that statements below throw keyword do not
execute. This can be overcome by placing the statements within finally block.
Throws Keyword:
Throws keyword is used in the signature of method to indicate that this method Might throw
an exception. The caller of this method must handle the exception using try-catch block.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as NullPointerException, it is programmers' fault that he is not
checking the code before it being used.
Different ways of handling the Exception
1) Handling the Exception(try-catch)
2) Re-throwing the Exception(try-catch-throw-throws-finally)
3) Ducking the Exception(throws)
1) Handling the exception:
If the methods in which exception occurs and the method in which exception handling is same
then it is called Handling the exception.
Program:
import java.util.Scanner;
public class TryCatchBlock
{
public void handlingException()
{
System.out.println(“Connection1 Established”);
Scanner s = new Scanner(System.in);
try
{
int a = s.nextInt();
int b = s.nextInt();
int c = a/b;
System.out.println(c);
catch(Exception e)
{
System.out.println("Exception occurs");
}
System.out.println(“Connection1 Terminated”);
}
}
class MainClass
{
public static void main(String args[])
{
System.out.println(“Connection1 Established”);
TryCatchBlock b = new TryCatchBlock();
b.handlingException();
System.out.println(“Connection1 Terminated”);
}
}
2) Re-throwing the Exception (try-catch-throw-throws-finally):
If an exception occurs within a method and is also handled, but the exception must also
propagate to the caller of the method, then it is referred to as re-throwing the exception.
To achieve this, me must use- try-catch-throw-throws-finally.
Program:
import java.util.Scanner;
public class RethrowException
{
public void handlingException()
{
System.out.println(“Connection2 Established”);
Scanner s = new Scanner(System.in);
try
{
int a = s.nextInt();
int b = s.nextInt();
int c = a/b;
System.out.println(c);
}
catch(Exception e)
{
System.out.println("Exception occurs");
throw e;
}
finally
{
System.out.println(“Connection2 Terminated”);
}
}
}
class MainClass
{
public static void main(String args[])
{
System.out.println(“Connection1 Established”);
try
{
RethrowException r = new RethrowException ();
r.handlingException();
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println(“Connection1 Terminated”);
}
}
3) Ducking the Exception(throws):
If an exception occurs within a method and the method does not want to handle it, instead it
wants to handover the responsibility of handling the exception to caller of the method, it is
referred to as ducking an exception. To achieve this, throws keyword is used.
Program:
import java.util.Scanner;
public class DuckingException
{
public void handlingException() throws Exception
{
System.out.println(“Connection2 Established”);
Scanner s = new Scanner(System.in);
int a = s.nextInt();
int b = s.nextInt();
int c = a/b;
System.out.println(c);
System.out.println(“Connection2 Terminated”);
}
}
class MainClass
{
public static void main(String args[])
{
System.out.println(“Connection1 Established”);
try
{
DuckingClass d = new DuckingClass ();
d.handlingException();
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println(“Connection1 Terminated”);
}
}
4.2.4 Class Throwable
The Throwable class is the superclass of every error and exception in the Java language. Only
objects that are one of the subclasses this class are thrown by any “Java Virtual Machine” or
may be thrown by the Java throw statement. For the motives of checking of exceptions during
compile-time, Throwable and any subclass of Throwable which is not also a subclass of
either Error or Runtime Exception are considered as checked exceptions.
Errors
Errors are usually beyond the control of the programmer, and we should not try to handle
errors.
StackOverflowError: When a function call is invoked by a Java application, a stack frame is
allocated on the call stack. The stack frame contains the parameters of the invoked method, its
local parameters, and the return address of the method. The return address denotes the
execution point from which, the program execution shall continue after the invoked method
returns. If there is no space for a new stack frame then, the StackOverflowError is thrown by
the Java Virtual Machine (JVM).
Program:
class OverFlow
{
void fun()
{
fun();
}
}
class OverFlowClass
{
public static void main(String args[])
{
OverFlow o = new OverFlow();
o.fun();
}
}
Output:
OutOfMemoryError: Usually, this error is thrown when the Java Virtual Machine cannot
allocate an object because it is out of memory, and no more memory could be made available
by the garbage collector.
Program:
class OutOfMemory
{
public static void main(String args[])
{
int a[] = new int[Integer. MAX_VALUE];
for(int i=0; i<a.length: i++){
System.out.println(a[i])
}
}
Output:
Similarity between Exception and Error
Error and Exception both occur during runtime.
In both cases Abrupt termination happens.
Differences between Exception and Error
4.2.5 Checked Exceptions in Java
These are the exceptions that are checked at compile time. If the code within a method throws
a checked exception, then the method must either handle the exception or it must specify the
exception using the throws keyword.
Program:
import java.io.FileInputStream;
public class CheckedException
public static void main(String args[])
FileInputStream f=new FileInputStream("java.txt");
System.out.print(f.read());
}
Output:
Program:
import java.io.FileInputStream;
public class CheckedException
public static void main(String args[])
try
FileInputStream f=new FileInputStream("mssg.txt");
int i = f.read();
while((i=f.read())!=-1){
System.out.print((char)i);
catch(Exception e)
System.out.println(e);
}
Output:
4.2.6 Unchecked Exceptions in Java
These are the exceptions that are not checked at compile time. In C++, all exceptions are
unchecked, so it is not forced by the compiler’s to either handle or specify the exception. It
is up to the programmers to specify or catch the exceptions.
Program:
class UncheckedException
{
public static void main(String args[])
{
String name = "Vishnu";
System.out.println(name);
if(name.equals("Vishnu"))
System.out.println("Same");
else
System.out.println("Not Same");
name = null;
System.out.println(name);
if(name.equals("Vishnu"))
System.out.println("Same");
else
System.out.println("Not Same");
}
}
Output:
Distinguish between Checked and Unchecked Exceptions
Checked Exceptions Unchecked Exceptions
1. Checked exceptions occur during compile 1. Unchecked exceptions occur during
time when the source code is being runtime when the program is in execution.
converted into an executable code.
2. The checked exception is checked by the 2. The compiler does not check these types
compiler. of exceptions.
3. Checked exceptions can be manually 3. Unchecked exceptions can also be
created. manually created.
4. The Java Virtual Machine requires the 4. The Java Virtual Machine does not
checked exception to be caught or handled. require the unchecked exception to be
caught or handled.
5. These types of exceptions can be handled 5. These types of exceptions cannot be a
at the time of compilation. catch or handle at the time of compilation,
because they get generated by the mistakes
in the program.
Examples of Checked exceptions: Examples of Unchecked Exceptions:
File Not Found Exception No Such Element Exception
No Such Field Exception Undeclared Throwable Exception
Interrupted Exception Empty Stack Exception
No Such Method Exception Arithmetic Exception
Class Not Found Exception Null Pointer Exception
Array Index Out of Bounds
Exception
Security Exception
4.2.7 Catching subclass exception
There are two types of problems associated with it
1. If the Super Class doesn’t declare an exception
2. If the Super Class declares an exception
1.If the Super Class doesn’t declare an exception
If Super Class doesn’t declare any exception then subclass does not declare with
checked exception
Program:
class Eagle
{
void eat()
{
System.out.println(“Eagle is eating”);
}
}
class GoldenEagle
{
void eat() throws IOException
{
System.out.println(“GoldenEagle is eating”);
}
}
If Super Class doesn’t declare any exception then SubClass may declare with
Unchecked exception.
Program:
class Eagle
{
void eat()
{
System.out.println(“Eagle is eating”);
}
}
class GoldenEagle
{
void eat() throws ArrayIndexOutofBoundsException
{
System.out.println(“GoldenEagle is eating”);
}
}
2. If the Super Class declares an exception
If the Super Class declares an exception then subclass must declare with same
Exception.
Program:
class Eagle
{
void eat() IOException
{
System.out.println(“Eagle is eating”);
}
}
class GoldenEagle
{
void eat() throws IOException
{
System.out.println(“GoldenEagle is eating”);
}
}
If the Super Class declares an exception then subclass can declare with its childclass
Exceptions
Program:
class Eagle
{
void eat() IOException
{
System.out.println(“Eagle is eating”);
}
}
class GoldenEagle
{
void eat() throws SQLException
{
System.out.println(“GoldenEagle is eating”);
}
}
4.2.8 Custom Exception
Java provides us the facility to create our own exceptions which are basically derived classes
of Exception. Creating our own Exception is known as a custom exception or user-defined
exception. Basically, Java custom exceptions are used to customize the exception according
to user needs. In simple words, we can say that a User-Defined Exception or custom
exception is creating your own exception class and throwing that exception using the ‘throw’
keyword.
Java exceptions cover almost all the general types of exceptions that may occur in the
programming. However, we sometimes need to create custom exceptions.
Creating CustomException should follow the below lines
Create a class and extend the Exception class.
Override the getMessage() and provide a suitable message.
Explicitly create an object of the class wherever there is need for an exception to be generated.
Program:
import java.util.Scanner;
class InvalidUserException extends Exception
{
public String getMessage()
{
return(“Invalid card details. Try again!”);
}
}
class ATM
{
int acc_num=1234;
int password = 9999;
int an, pwd;
void acceptInput()
{
Scanner s = new Scanner(System.in);
System.out.println(“Enter the acc_num”);
an = scan.nextInt();
System.out.println(“Enter the password”);
pwd = scan.nextInt();
}
void verify() throws Exception
{
if(acc_num == an && password == pwd)
{
System.out.println(“Collect your money”);
}
else
{
InvalidUserException i = new InvalidUserException();
System.out.println(i.getMessage());
throw i;
}
}
}
class Bank
{
void initiate()
{
ATM a = new ATM();
try
{
a.acceptInput();
a.verify();
}
catch(Exception e)
{
try
{
a.acceptInput();
a.verify();
}
catch(Exception f)
{
try
{
a.acceptInput();
a.verify();
}
catch(Exception g)
{
System.out.println(”Card Blocked”
System.exit(0);
}
}
}
}
}
class CustomException
{
public static void main(String args[])
{
Bank b = new Bank();
b.initiate();
}
}
Output: