0% found this document useful (0 votes)
5 views27 pages

Java Inheritance and Exception Handling

The document covers key concepts of inheritance in Java, including types of inheritance (single, multilevel, hierarchical, multiple, and hybrid), the use of the super keyword, and the final keyword. It also explains abstract classes, interfaces, and the creation and importance of packages in Java. Additionally, it discusses exception handling and the significance of the CLASSPATH and java.lang package.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views27 pages

Java Inheritance and Exception Handling

The document covers key concepts of inheritance in Java, including types of inheritance (single, multilevel, hierarchical, multiple, and hybrid), the use of the super keyword, and the final keyword. It also explains abstract classes, interfaces, and the creation and importance of packages in Java. Additionally, it discusses exception handling and the significance of the CLASSPATH and java.lang package.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

UNIT-III

Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class.
Interfaces, creating the packages, using packages, importance of CLASSPATH and [Link]
package. Exception handling, importance of try, catch, throw, throws and finally block, user-
defined exceptions, Assertions.
INHERITANCE
Inheritance can be defined as the process where one class acquires the properties (methods
and fields) of another. With the use of inheritance the information is made manageable in a
hierarchical order.
The class which inherits the properties of other is known as subclass (derived class, child
class) and the class whose properties are inherited is known as superclass (base class, parent class).
Inheritance defines is-a relationship between a Super class and its Sub class. extends and
implements keywords are used to describe inheritance in Java.
extends keyword:
extends is the keyword used to inherit the properties of a class. Following is the syntax of extends
keyword.
Let us see how extend keyword is used to achieve Inheritance.
class Vehicle
{
......
}
class Car extends Vehicle
{
....... //extends the property of vehicle class.
}
Now based on above example. In OOPs term we can say that,
 Vehicle is super class of Car.
 Car is sub class of Vehicle.
 Car IS-A Vehicle.
Advantages of Inheritance:
Code Reusability -- facility to use public methods of base class without rewriting the same
Extensibility -- extending the base class logic as per business logic of the derived class
Data hiding -- base class can decide to keep some data private so that it cannot be altered by the
derived class
Overriding--With inheritance, we will be able to override the methods of the base class so that
meaningful implementation of the base class method can be designed in the derived class.
Disadvantages of Inheritance:
1. Both classes (super and subclasses) are tightly-coupled.
2. As they are tightly coupled (binded each other strongly with extends keyword), they cannot
work independently of each other.
3. Changing the code in super class method also affects the subclass functionality.
4. If super class method is deleted, the code may not work as subclass may call the super class
method with super keyword. Now subclass method behaves independently.

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, [Link], MISTE
Training and Placement Officer
Types of inheritance:
Below are the different types of inheritance which is supported by Java.
1. Single Inheritance in Java:
Single Inheritance is the simple inheritance of all, When a class extends another class(Only one
class) then we call it as Single inheritance. The below diagram represents the single inheritance in
java where Class B extends only one class Class A. Here Class B will be the Sub class and Class A will
be one and only Super class.

2. Multilevel Inheritance in Java:


In Multilevel Inheritance a derived class will be inheriting a parent class and as well as the derived
class act as the parent class to other class. As seen in the below diagram. ClassB inherits the
property of Class A and again Class B act as a parent for Class C. In Short Class A parent for Class B
and Class B parent for Class C.

3. Hierarchical Inheritance in Java:


In Hierarchical inheritance one parent class will be inherited by many sub classes. As per the below
example Class A will be inherited by Class B and Class C. Class A will be acting as a parent class for
Class B and Class C

4. Multiple Inheritance in Java:


Multiple Inheritance is nothing but one class extending more than one class. Multiple Inheritance
is basically not supported by many Object Oriented Programming languages such as Java, Small
Talk, C# etc.. (C++ Supports Multiple Inheritance). As the Child class has to manage the
dependency of more than one Parent class. But you can achieve multiple inheritance in Java using
Interfaces.

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, [Link], MISTE
Training and Placement Officer
Hybrid Inheritance in Java:
Hybrid Inheritance is the combination of both Single and Multiple Inheritance. Again Hybrid
inheritance is also not directly supported in Java only through interface we can achieve this. Flow
diagram of the Hybrid inheritance will look like below. As you can Class A will be acting as the
Parent class for Class B & Class C and Class B & Class C will be acting as Parent for Class D.

A very important fact to remember is that Java does not support multiple inheritance. This means
that a class cannot extend more than one class. Therefore following is illegal:
public class extends Animal, Mammal { }
However, a class can implement one or more interfaces. This has made Java get rid of the
impossibility of multiple inheritance.
super keyword
super keyword is used to call a super class constructor and to call or access super class
members(instance variables or methods).
syntax of super :
=> super(arg-list)
When a subclass calls super() it is calling the constructor of its immediate superclass.
super() must always be the first statement executed inside a subclass constructor.
=> [Link]
Here member can be either method or an instance variables.
This second form of super is most applicable to situation in which member names of a subclass hide
member of super class due to same name.
The super keyword in java is a reference variable that is used to refer parent class objects.
The keyword “super” came into the picture with the concept of Inheritance. It is majorly used in
the following contexts:
1. Use of super with variables: This scenario occurs when a derived class and base class has same
data members. In that case there is a possibility of ambiguity for the JVM. We can understand it
more clearly using this code snippet:

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, [Link], MISTE
Training and Placement Officer
/* Base class vehicle */
class Vehicle
{
int maxSpeed = 120;
}
/* sub class Car extending vehicle */
class Car extends Vehicle
{
int maxSpeed = 180;
void display()
{
/* print maxSpeed of base class (vehicle) */
[Link]("Maximum Speed: " + [Link]);
}
}
/* Driver program to test */
class Test
{
public static void main(String[] args)
{
Car small = new Car();
[Link]();
}
}
Output: Maximum Speed: 120
In the above example, both base class and subclass have a member maxSpeed. We could access
maxSpeed of base class in sublcass using super keyword.
2. Use of super with methods: This is used when we want to call parent class method. So whenever a
parent and child class have same named methods then to resolve ambiguity we use super keyword. This
code snippet helps to understand the said usage of super keyword.
/* Base class Person */
class Person
{
void message()
{
[Link]("This is person class");
}
}
/* Subclass Student */
class Student extends Person
{
void message()
{
[Link]("This is student class");
}
// Note that display() is only in Student class
void display()

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, [Link], MISTE
Training and Placement Officer
{
// will invoke or call current class message() method
message();
// will invoke or call parent class message() method
[Link]();
}
}
/* Driver program to test */
class Test
{
public static void main(String args[])
{
Student s = new Student();
// calling display() of Student
[Link]();
}
}
Output: This is student class
This is person class
In the above example, we have seen that if we only call method message() then, the current class
message() is invoked but with the use of super keyword, message() of superclass could also be
invoked.
3. Use of super with constructors: super keyword can also be used to access the parent class
constructor. One more important thing is that, ‘’super’ can call both parametric as well as non parametric
constructors depending upon the situation. Following is the code snippet to explain the above concept:
/* superclass Person */
class Person
{
Person()
{
[Link]("Person class Constructor");
}
}
/* subclass Student extending the Person class */
class Student extends Person
{
Student()
{
// invoke or call parent class constructor
super();

[Link]("Student class Constructor");


}
}
/* Driver program to test*/
class Test
{

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, [Link], MISTE
Training and Placement Officer
public static void main(String[] args)
{
Student s = new Student();
}
}
Output: Person class Constructor
Student class Constructor
In the above example we have called the superclass constructor using keyword ‘super’ via subclass
constructor.
In constructor, default constructor is provided by compiler automatically but it also adds
super() before the first statement of constructor. If you are creating your own constructor and you
do not have either this() or super() as the first statement, compiler will provide super() as the first
statement of the constructor.
final keyword
final keyword is used in different contexts. First of all, final is a non-access modifier applicable only
to a variable, a method or a class.
Following are different contexts where final is used.
1. final Variables can not change its value.
2. final Methods can not be Overridden or Over Loaded
3. final Classes can not be extended or inherited
1. Java final variable:
If you make any variable as final, you cannot change the value of final variable(It will be constant).
Example of final variable:
There is a final variable speedlimit, we are going to change the value of this variable, but It can't be
changed because final variable once assigned a value can never be changed.
1. class Bike{
2. final int speedlimit=90;//final variable
3. void run(){
4. speedlimit=400;
5. }
6. public static void main(String args[]){
7. Bike obj=new Bike();
8. [Link]();
9. }
10. }//end of class
Output: Compile Time Error
2. Java final method: If you make any method as final, you cannot override it.
Example of final method:
1. class Bike{
2. final void run(){[Link]("running");}
3. }
4. class Honda extends Bike{
5. void run(){
6. [Link]("running safely with 100kmph");}
7. public static void main(String args[]){
8. Honda honda= new Honda();

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, [Link], MISTE
Training and Placement Officer
9. [Link]();
10. }
11. }
Output:Compile Time Error
3. Java final class: If you make any class as final, you cannot extend it.
Example of final class:
1. final class Bike{
2. }
3. class Honda1 extends Bike{
4. void run(){
5. [Link]("running safely with 100kmph");}
6. public static void main(String args[]){
7. Honda1 honda= new Honda();
8. [Link]();
9. }
10. }
Output:Compile Time Error
Q) Is final method inherited?
Ans) Yes, final method is inherited but you cannot override it.
1. class Bike{
2. final void run(){[Link]("running...");}
3. }
4. class Honda2 extends Bike{
5. public static void main(String args[]){
6. new Honda2().run();
7. }
8. }
abstract class
A class that is declared with abstract keyword, is known as abstract class in java. It can have
abstract and non-abstract methods (method with body).
Before learning java abstract class, let's understand the abstraction in java first.
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to the
user.
Another way, it shows only important things to the user and hides the internal details for example
sending sms, you just type the text and send the message. You don't know the internal processing
about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
Ways to achieve Abstraction:
There are two ways to achieve abstraction in java
1. Abstract class (0 to 100%)
2. Interface (100%)
Any class that contains one or more abstract methods must also be declared as abstract. Such
types of classes are known as abstract classes.
Let us consider the following example:
abstract class A

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, [Link], MISTE
Training and Placement Officer
{
abstract void callme();
void call()
{
[Link](“Kumar sir”);
}
}
class B extends A
{
void callme()
{
[Link](“GOOD MORNING”);
}
}
class abstractdemo
{
public static void main(String args[]){
B b=new B();
[Link]();
[Link]();
}
}
Output:GOOD MORINING
Kumar sir
INTERFACES
Interface looks like a class but it is not a class. An interface can have methods and variables
just like the class but the methods declared in interface are by default abstract (only method
signature, no body). Also, the variables declared in an interface are public, static and final by
default.
Interfaces are declared by specifying a keyword “interface”.
Syntax :
interface <interface_name>
{
// declare constant fields
// declare methods that abstract
// by default.
}
To implement interface use implements keyword.
 Interfaces, like abstract classes cannot be instantiated.
 Interfaces does not contain concrete methods.
 Interfaces can only be “implemented” by other classes or “extended” by other interfaces.
 Interfaces support multiple inheritance which is not supported by classes.
A class can only extend a single class, but can implement one or more interfaces.
 An interface in java is a blueprint of a class. It has static constants and abstract methods.
 The interface in java is a mechanism to achieve abstraction.

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, [Link], MISTE
Training and Placement Officer
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known as
multiple inheritance.

Java Interface Example: Bank


Let's see example of java interface which provides the implementation of Bank interface.
1. interface Bank{
2. float rateOfInterest();
3. }
4. class SBI implements Bank{
5. public float rateOfInterest(){return 9.15f;}
6. }
7. class PNB implements Bank{
8. public float rateOfInterest(){return 9.7f;}
9. }
10. class TestInterface2{
11. public static void main(String[] args){
12. Bank b=new SBI();
13. [Link]("ROI: "+[Link]());
14. }}
Output: ROI: 9.15
Extending Interfaces:
•After declaring an interface and implementing the interface, in future at some point of time if we
decide to add one or more new methods to the existing interface, then the classes which
implements the interface will break.
•To prevent such breaking the existing interface can be extended by a new interface in which the
additional methods are declared.
•Now, the class can simply implement the new interface and provide implementations for the new
methods.
Applying Interfaces:
•Since interfaces cannot be instantiated, we will use the interfaces in our programs by using the
concept, “Assigning an object of a one type to a variable/reference of a another type”.
•Here the one type will be the interface and another type will be the class which implements the
interface.
•So, we can assign the object of a class which implements the interface to a variable/reference of
the type, interface.
Example: Bank b=new SBI();

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, [Link], MISTE
Training and Placement Officer
CREATING THE PACKAGES
In general, a Java source file can contain any (or all) of the following four internal parts:
• A single package statement (optional)
• Any number of import statements (optional)
• A single public class declaration (required)
• Any number of classes private to the package (optional)
Java provides a mechanism for partitioning the class name space into more manageable chunks.
This mechanism is the package. You can define classes inside a package that are not accessible by
code outside that package. You can also define class members that are only exposed to other
members of the same package.
DEFINING A PACKAGE
 A package is a collection of related classes.
 To create a package is quite easy: simply include a package command as the first statement
in a Java source file.
 Any classes declared within that file will belong to the specified package.
 The package statement defines a name space in which classes are stored.
 If you omit the package statement, the class names are put into the default package, which
has no name. (This is why you haven’t had to worry about packages before now.)
 Packages are used to avoid naming conflicts of classes.
 Packages act as containers for classes. Means a package contains classes.
 We can declare a class with same name in different packages.
The general form of the package statement:
package pkg;
Here, pkg is the name of the package.
For example, the following statement creates a package called MyPackage.
package MyPackage;
You can create a hierarchy of packages. To do so, simply separate each package name from the one
above it by use of a period. The general form of a multileveled package statement is shown here:
package pkg1[.pkg2[.pkg3]];
For example, a package declared as package [Link]; needs to be stored in
java/awt/image

Packages in Java are a way of grouping similar types of classes / interfaces together. It is a great
way to achieve reusability. We can simply import a class providing the required functionality from
an existing package and use it in our program. A package basically acts as a container for group of
related classes. The concept of package can be considered as means to achieve data encapsulation
Packages are categorized as :
1 ) Built-in packages ( standard packages which come as a part of Java Runtime Environment )
2 ) User-defined packages ( packages defined by programmers to bundle group of related classes )
Built-in Packages:
These packages consists of a large number of classes which are a part of Java API. For e.g, we have
used [Link] package previously which contain classes to support input / output operations in Java.
Similarly, there are other packages which provides different functionality.

Some of the commonly used built-in packages are shown in the table below :
Package Description

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, [Link], MISTE
Training and Placement Officer
Name
Contains language support classes ( for e.g classes which defines primitive data
[Link]
types, math operations, etc.) . This package is automatically imported.
[Link] Contains classes for supporting input / output operations.
Contains utility classes which implement data structures like Linked List, Hash
[Link]
Table, Dictionary, etc and support for Date / Time operations.
[Link] Contains classes for creating Applets.
Contains classes for implementing the components of graphical user interface ( like
[Link]
buttons, menus, etc. ).
[Link] Contains classes for supporting networking operations.
Accessing classes in a package
Consider the following statements :
1 ) import [Link]; // import the Vector class from util package
2 ) import [Link].*; // import all the class from util package
First statement imports Vector class from util package which is contained inside java package.
Second statement imports all the classes from util package.
User-defined packages:
Declaring a Package:
•Java provides the keyword “package” for declaring a package.
•Syntax for declaring a package is as follows:
package package-name;
•Example for declaring a package is as follows:
package mypackage;
•Package declaration must be the first statement in the program.
•Generally the package names are written in lower case.
•Java uses file system directories to maintain packages.
•If no package is declared in the program, then it will be treated as a default package which has
no name.
•So, in the above example, since mypackage is a packages, we must create a folder with the
name “mypackage” in the development directory.

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, [Link], MISTE
Training and Placement Officer
So, now the package “mypackage” contains three classes, Shape, Rectangle and ShapeDemo.

ACCESSING A PACKAGE OR USAGE OF PACKAGES and Importance of CLASSPATH


•How does the JVM know where the packages are located?
•There three ways using which the JVM can locate the packages. They are:
1) By default
2) By setting CLASSPATH environment variable
3) By using the –classpath option available with the “java” command

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, [Link], MISTE
Training and Placement Officer
Importing a Package:After creating a package, the classes available in the package can be used
in other programs. For using the predefined classes available in a package, the package must be
imported.
There are three ways of importing the classes available in the package. They are:
1) Importing all the classes in the package.
2) Importing only the specific class in the package.
3) Using the fully qualified name.

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, [Link], MISTE
Training and Placement Officer
Multilevel Packages:
•Packages can be maintained in hierarchical manner.
•The syntax for such multilevel packages is as follows:
package pkg1.pgkg2.pkg3;
•Java maintains the packages as folders. So the above multilevel packages are maintained as:
pkg1\pkg2\pkg3
[Link] package
[Link] package contains the classes that are fundamental to the design of the Java programming
language. It is Java’s most widely used package.
[Link] includes the following classes:

There are also two classes defined by the Character class: [Link] and
[Link].
[Link] defines the following interfaces:

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, [Link], MISTE
Training and Placement Officer
EXCEPTION HANDLING
• An exception is a run-time error. Exception can also be defined as an abnormal or
unexpected condition that’s occurs at run-time (when executing the program).
• The process of handling exceptions is known as Exception Handling.
•Exceptions can be generated by the Java run-time system or manually generated by the code in
the program.
•Exceptions generated by the Java run-time system are handled by the Java run-time itself.
•Manually created exceptions must be handled by the programmer.
•Java provides five keywords for exception handling. They are:
1) try
2) catch
3) throw
4) throws
5) finally
•try: Any statements that may raise an exception are included in the “try” block. Every “try” block
requires atleast one “catch” or “finally” block.
•catch: The exception handling code is provided in the “catch” block.
•throw: System-generated exceptions are thrown by the Java run-time system. To manually throw
an exception, use the keyword throw.
•throws: Any exception that is thrown out of a method must be specified as such by a throws
clause.
•finally: Any code that must be executed whether or not an exception occurs is written in the
“finally” block.
This is the general form of an exception-handling block:
try {
// block of code to monitor for errors
}
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
}
Here, ExceptionType is the type of exception that has occurred.
Benefits of Exception Handling:
1. It is used to handle runtime errors
2. Exception handling allows us to control the normal flow of the program by using exception
handling in program.
3. It throws an exception whenever a calling method encounters an error providing that the
calling method takes care of that error.
4. It also gives us the scope of organizing and differentiating between different error types
using a separate block of codes. This is done with the help of try-catch blocks.

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, [Link], MISTE
Training and Placement Officer
5. Separating Error-Handling Code from "Regular" Code: Exceptions provide the means to
separate the details of what to do when something out of the ordinary happens from the
main logic of a program. In traditional programming, error detection, reporting, and
handling often lead to confusing spaghetti code. Exceptions enable you to write the main
flow of your code and to deal with the exceptional cases elsewhere.
6. Propagating Errors Up the Call Stack: A second advantage of exceptions is the ability to
propagate error reporting up the call stack of methods.
7. Grouping and Differentiating Error Types: Because all exceptions thrown within a program
are objects, the grouping or categorizing of exceptions is a natural outcome of the class
hierarchy.
IMPORTANCE of try and catch
What is try Block?
The try block contains a block of program statements within which an exception might occur. A try
block is always followed by a catch block, which handles the exception that occurs in associated try
block. A try block must followed by a catch block or finally block or both.
Syntax of try block:
try
{
//statements that may cause an exception
}
What is catch Block?
A catch block must be associated with a try block. The corresponding catch block executes if an
exception of a particular type occurs within the try block. For example if an arithmetic exception
occurs in try block then the statements enclosed in catch block for arithmetic exception executes.
Syntax of try catch in java:
try
{
//statements that may cause an exception
}
catch (exception(type) e(object))
{
//error handling code
}
Flow of try catch block:
1. If an exception occurs in try block then the control of execution is passed to the catch block
from try block. The exception is caught up by the corresponding catch block. A single try
block can have multiple catch statements associated with it, but each catch block can be
defined for only one exception class. The program can also contain nested try-catch-finally
blocks.
2. After the execution of all the try blocks, the code inside the finally block executes. It is not
mandatory to include a finally block at all, but if you do, it will run regardless of whether an
exception was thrown and handled by the try and catch blocks.
An example of try catch in Java
class Example1 {
public static void main(String args[]) {
int num1, num2;

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, [Link], MISTE
Training and Placement Officer
try {
// Try block to handle code that may cause exception
num1 = 0;
num2 = 18 / num1;
[Link]("Try block message");
} catch (ArithmeticException e) {
// This block is to catch divide-by-zero error
[Link]("Error: Don't divide a number by zero");
}
[Link]("I'm out of try-catch block in Java.");
}
}
Output:
Error: Don't divide a number by zero
I'm out of try-catch block in Java.
Multiple catch blocks in Java
1. A try block can have any number of catch blocks.
2. A catch block that is written for catching the class Exception can catch all other exceptions
Syntax:
catch(Exception e)
{
//This catch block catches all the exceptions
}
3. If multiple catch blocks are present in a program then the above mentioned catch block should
be placed at the last as per the exception handling best practices.
4. If the try block is not throwing any exception, the catch block will be completely ignored and the
program continues.
5. If the try block throws an exception, the appropriate catch block (if one exists) will catch it
–catch(ArithmeticException e) is a catch block that can catch ArithmeticException
–catch(NullPointerException e) is a catch block that can catch NullPointerException
6. All the statements in the catch block will be executed and then the program continues.
Example of Multiple catch blocks
class Example2{
public static void main(String args[]){
try{
int a[]=new int[7];
a[4]=30/0;
[Link]("First print statement in try block");
}
catch(ArithmeticException e){
[Link]("Warning: ArithmeticException");
}
catch(ArrayIndexOutOfBoundsException e){
[Link]("Warning: ArrayIndexOutOfBoundsException");
}
catch(Exception e){

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, [Link], MISTE
Training and Placement Officer
[Link]("Warning: Some Other exception");
}
[Link]("Out of try-catch block...");
}
}
Output:
Warning: ArithmeticException
Out of try-catch block...
In the above example there are multiple catch blocks and these catch blocks executes sequentially
when an exception occurs in try block. Which means if you put the last catch block
( catch(Exception e)) at the first place, just after try block then in case of any exception this block
will execute as it has the ability to handle all exceptions. This catch block should be placed at the
last to avoid such situations.
Nested try statements : Sometimes a situation may arise where a part of a block may cause one
error and the entire block itself may cause another error. In such cases, exception handlers have to
be nested.
The try statement can be nested.
That is, a try statement can be inside a block of another try.
Each time a try statement is entered, its corresponding catch block has to entered.
Syntax:
1. ....
2. try
3. {
4. statement 1;
5. statement 2;
6. try
7. {
8. statement 1;
9. statement 2;
10. }
11. catch(Exception e)
12. {
13. }
14. }
15. catch(Exception e)
16. {
17. }
18. ....
Java nested try example
Let's see a simple example of java nested try block.
import [Link];
public class Nested {
public static void main(String[] args) {
try {
[Link]("Outer try block starts");
try {

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, [Link], MISTE
Training and Placement Officer
[Link]("Inner try block starts");
int res = 5 / 0;
} catch (InputMismatchException e) {
[Link]("InputMismatchException caught");
} finally {
[Link]("Inner final");
}
} catch (ArithmeticException e) {
[Link]("ArithmeticException caught");
} finally {
[Link]("Outer finally");
}
}
}
Output:
Outer try block starts
Inner try block starts
Inner final
ArithmeticException caught
Outer finally Outer finally
throw keyword or User defined Exceptions
The throw keyword is used to explicitly throw an exception. We can throw either checked
or unchecked exception. The throw keyword is mainly used to throw custom exceptions or user
defined exceptions.
We can create our own exception sub class simply by extending java Exception class. You
can define a constructor for your Exception sub class (not compulsory) and you can override the
toString() function to display your customized message on catch.
// Java program to illustrate the use of throw
class VoteException extends Exception
{
VoteException(String s)
{
super(s);
}
}
class Examplethrow
{
static void validate(int age) throws VoteException
{
if(age < 18)
throw new VoteException("Candidate is not eligible to vote");
else
[Link]("Welcome to Vote");
}
public static void main(String args[])
{

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, [Link], MISTE
Training and Placement Officer
try
{
validate(13);
}
catch(Exception e)
{
[Link]("Exception occured: "+e);
}
[Link]("End of the program");
}
}
Output:
Exception occured: VoteException: Candidate is not eligible to vote
End of the program
throws keyword
The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception so it is better for the programmer to provide the
exception handling code so that normal flow can be [Link] a method is using throws clause
along with few exceptions then this implicitly tells other methods that – “ If you call me, you must
handle these exceptions that I throw”.
Syntax of java throws
returntype method-name(parameter-list) throws exception-list
{
// body of method
}
Here, exception-list is a comma-separated list of the exceptions that a method can throw.
Which exception should be declared
Ans) checked exception only, because:
 unchecked Exception: under your control so correct your code.
 error: beyond your control e.g. you are unable to do anything if there occurs
VirtualMachineError or StackOverflowError.
Rule: If you are calling a method that declares an exception, you must either caught or declare
the exception.
Case1:You caught the exception i.e. handle the exception using try/catch.
Case2:You declare the exception i.e. specifying throws with the method.
We already discussed case 1: how to handle exception using try/catch in the above
Case2: You declare the exception
A )In case you declare the exception, if exception does not occur, the code will be executed fine.
B )In case you declare the exception if exception occurs, an exception will be thrown at runtime
because throws does not handle the exception.
A)Program if exception does not occur
1. import [Link].*;
2. class M{
3. void method()throws IOException{
4. [Link]("device operation performed");
5. }

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, [Link], MISTE
Training and Placement Officer
6. }
7. class Testthrows3{
8. public static void main(String args[])throws IOException{//declare exception
9. M m=new M();
10. [Link]();
11. [Link]("normal flow...");
12. }
13. }
Output: device operation performed
normal flow...
B)Program if exception occurs
1. import [Link].*;
2. class M{
3. void method()throws IOException{
4. throw new IOException("device error");
5. }
6. }
7. class Testthrows4{
8. public static void main(String args[])throws IOException{//declare exception
9. M m=new M();
10. [Link]();
11. [Link]("normal flow...");
12. }
13. }
Output: Runtime Exception

Difference between throw and throws in Java


There are many differences between throw and throws keywords. A list of differences between
throw and throws are given below:
No. throw throws
Java throw keyword is used to explicitly throw Java throws keyword is used to declare an
1)
an exception. exception.
Checked exception cannot be propagated Checked exception can be propagated with
2)
using throw only. throws.
3) Throw is followed by an instance. Throws is followed by class.
4) Throw is used within the method. Throws is used with the method signature.
You can declare multiple exceptions e.g.
5) You cannot throw multiple exceptions. public void method()throws IOException,
SQLException.
finally keyword
Java finally block is a block that is used to execute important code such as closing connection,
stream etc.
Java finally block is always executed whether exception is handled or not.
Java finally block must be followed by try or catch block.

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, [Link], MISTE
Training and Placement Officer
 finally block in java can be used to put "cleanup" code such as closing a file, closing
connection etc.
Rule: For each try block there can be zero or more catch blocks, but only one finally block.
Note: The finally block will not be executed if program exits(either by calling [Link]() or by
causing a fatal error that causes the process to abort).
Syntax of finally block
try
{
//statements that may cause an exception
}
finally
{
//statements to be executed
}
Cases when they finally block doesn’t execute
The circumstances that prevent execution of the code in a finally block are:
– The death of a Thread
– Using of the System. exit() method.
– Due to an exception arising in the finally block.
Example: Below example illustrates finally block execution when exception occurs in try block but
doesn’t get handled in catch block.
class Examplethrows{
public static void main(String args[]){
try{
[Link]("First statement of try block");
int num=61/0;
[Link](num);
}
catch(ArrayIndexOutOfBoundsException e){
[Link]("ArrayIndexOutOfBoundsException");
}
finally{
[Link]("finally block");
}
[Link]("Out of try-catch-finally block");
}
}
Output:
First statement of try block
finally block
Exception in thread "main" [Link]: / by zero
at [Link]([Link])

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, [Link], MISTE
Training and Placement Officer
Note: If you don't handle exception, before terminating the program, JVM executes finally
block(if any).
Difference between final, finally and finalize
There are many differences between final, finally and finalize. A list of differences between final,
finally and finalize are given below:

No. Final finally finalize


Final is used to apply restrictions on class, Finally is used to place Finalize is used to
method and variable. Final class can't be important code, it will be perform clean up
1) inherited, final method can't be executed whether processing just before
overridden and final variable value can't exception is handled or object is garbage
be changed. not. collected.
2) Final is a keyword. Finally is a block. Finalize is a method.
Java final example
1. class FinalExample{
2. public static void main(String[] args){
3. final int x=100;
4. x=200;//Compile Time Error
5. }}
Java finally example
1. class FinallyExample{
2. public static void main(String[] args){
3. try{
4. int x=300;
5. }catch(Exception e){[Link](e);}
6. finally{[Link]("finally block is executed");}
7. }}
Java finalize example
1. class FinalizeExample{
2. public void finalize(){[Link]("finalize called");}
3. public static void main(String[] args){
4. FinalizeExample f1=new FinalizeExample();
5. FinalizeExample f2=new FinalizeExample();
6. f1=null;
7. f2=null;
8. [Link]();
9. }}

EXCEPTION HIERARCHY:

In Java, exception can be checked or unchecked. They both fit into a class hierarchy. The
following diagram shows Java Exception classes hierarchy.

Underlined are checked exceptions. Any checked exceptions that may be thrown in a
method must either be caught or declared in the method's throws clause. Checked exceptions

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, [Link], MISTE
Training and Placement Officer
must be caught at compile time. Checked exceptions are so called because both the Java compiler
and the Java virtual machine check to make sure this rule is obeyed.

Remaining is unchecked exceptions. They are exceptions that are not expected to be
recovered, such as null pointer, divide by 0, etc.

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, [Link], MISTE
Training and Placement Officer
BVCITS –BATLAPALEM Prepared By,
A P V D L Kumar, [Link], MISTE
Training and Placement Officer
Java defines several exception classes inside the standard package [Link].

The list of unchecked exceptions or the exception classes which extend from RuntimeException:
Exception Description
ArithmeticException Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds.
ArrayStoreException Assignment to an array element of an incompatible type.
ClassCastException Invalid cast.
IllegalArgumentException Illegal argument used to invoke a method.
IllegalMonitorStateException Illegal monitor operation, such as waiting on an unlocked thread.
IllegalStateException Environment or application is in incorrect state.
IllegalThreadStateException Requested operation not compatible with current thread state.
IndexOutOfBoundsException Some type of index is out-of-bounds.
NegativeArraySizeException Array created with a negative size.
NullPointerException Invalid use of a null reference.
NumberFormatException Invalid conversion of a string to a numeric format.
SecurityException Attempt to violate security.
StringIndexOutOfBounds Attempt to index outside the bounds of a string.
UnsupportedOperationException An unsupported operation was encountered.

Following is the list of Java Checked Exceptions Defined in [Link]:

Exception Description
ClassNotFoundException Class not found.
Attempt to clone an object that does not implement the Cloneable
CloneNotSupportedException
interface.
IllegalAccessException Access to a class is denied.
InstantiationException Attempt to create an object of an abstract class or interface.
InterruptedException One thread has been interrupted by another thread.
NoSuchFieldException A requested field does not exist.
NoSuchMethodException A requested method does not exist.
ASSERTIONS
Assertion is a statement in java. It can be used to test your assumptions about the program.
While executing assertion, it is believed to be true. If it fails, JVM will throw an error named
AssertionError. It is mainly used for testing purpose.
Advantage of Assertion:
It provides an effective way to detect and correct programming errors.
Syntax of using Assertion:
There are two ways to use assertion.
First way is:
assert expression;
Second way is:
assert expression1 : expression2;

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, [Link], MISTE
Training and Placement Officer
Simple Example of Assertion in java:
import [Link];
class AssertionExample
{
public static void main( String args[] )
{
Scanner scanner = new Scanner( [Link] );
[Link]("Enter your age ");
int value = [Link]();
assert value>18:" Not eligible to vote";
[Link]("You are eligible to vote");
}
}
If you use assertion, It will not run simply because assertion is disabled by default. To enable the
assertion, -ea or -enableassertions switch of java must be used.
Compile it by: javac [Link]
Run it by: java -ea AssertionExample
Output:
Enter your age 11
Exception in thread "main" [Link]: Not eligible to vote
at [Link]([Link])

*************************BVCITS- DEPARTMENT OF CSE****************************

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, [Link], MISTE
Training and Placement Officer

You might also like