0% found this document useful (0 votes)
27 views62 pages

Java Basic Unit 3

The document discusses inheritance, interfaces, abstract classes, and exceptions in Java. It defines inheritance and the different types of inheritance like single, multilevel, and hierarchical inheritance. It also explains abstract classes and methods, and why multiple inheritance is not supported in Java.

Uploaded by

afnaan31250
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
27 views62 pages

Java Basic Unit 3

The document discusses inheritance, interfaces, abstract classes, and exceptions in Java. It defines inheritance and the different types of inheritance like single, multilevel, and hierarchical inheritance. It also explains abstract classes and methods, and why multiple inheritance is not supported in Java.

Uploaded by

afnaan31250
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 62

UNIT-III

INHERITANCE, INTERFACE AND EXCEPTIONS


Types of inheritance-Super and Final -Interface-Abstract Classes- Interface vs Abstract
classes -Packages-Creating Packages -access protection - Exception handling, importance of
try, catch, throw, throws and finally block, user defined exceptions, Assertions. [8 Hours]

Inheritance in Java
• Inheritance in Java is a mechanism in which one object acquires all the
properties and behaviors of a parent object.
• The idea behind inheritance in Java is that you can create new classes that are
built upon existing classes.
• When you inherit from an existing class, you can reuse methods and fields of
the parent class. Moreover, you can add new methods and fields in your
current class also.
• Inheritance represents the IS-A relationship which is also known as a parent-
child relationship.

Why use inheritance in java

o For Method Overriding (so runtime polymorphism can be achieved).


o For Code Reusability.

Terms used in Inheritance

o Class: A class is a group of objects which have common properties. It is a template or


blueprint from which objects are created.
o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also
called a derived class, extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.
o Reusability: As the name specifies, reusability is a mechanism which facilitates you to
reuse the fields and methods of the existing class when you create a new class. You
can use the same fields and methods already defined in the previous class.

The syntax of Java Inheritance


1. class Subclass-name extends Superclass-name
2. {
3. //methods and fields
4. }

The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.

In the terminology of Java, a class which is inherited is called a parent or superclass, and the
new class is called child or subclass.

Java Inheritance Example

As displayed in the above figure, Programmer is the subclass and Employee is the
superclass. The relationship between the two classes is Programmer IS-A Employee.
It means that Programmer is a type of Employee.

1. class Employee{
2. float salary=40000;
3. }
4. class Programmer extends Employee{ 0
5. int bonus=10000;
6. public static void main(String args[]){
7. Programmer p=new Programmer();
8. System.out.println("Programmer salary is:"+p.salary);
9. System.out.println("Bonus of Programmer is:"+p.bonus);
10. }
11. }
Programmer salary is:40000.0
Bonus of programmer is:10000

In the above example, Programmer object can access the field of own class as well as
of Employee class i.e. code reusability.

Types of inheritance in java


• On the basis of class, there can be three types of inheritance in java: single,
multilevel and hierarchical.
• In java programming, multiple and hybrid inheritance is supported through
interface only.

Note: Multiple inheritance is not supported in Java through class.

When one class inherits multiple classes, it is known as multiple inheritance. For
Example:
Single Inheritance Example
When a class inherits another class, it is known as a single inheritance. In the example
given below, Dog class inherits the Animal class, so there is the single inheritance.

1. class Animal{
2. void eat()
3. {System.out.println("eating...");}
4. }
5. class Dog extends Animal{
6. void bark()
7. {System.out.println("barking...");}
8. }
9. class TestInheritance{
10. public static void main(String args[]){
11. Dog d=new Dog();
12. d.bark();
13. d.eat();
14. }}

Output:

barking...
eating...
Multilevel Inheritance Example
When there is a chain of inheritance, it is known as multilevel inheritance.

As you can see in the example given below, BabyDog class inherits the Dog class
which again inherits the Animal class, so there is a multilevel inheritance.

1. class Animal{
2. void eat()
3. {System.out.println("eating...");}
4. }
5. class Dog extends Animal{
6. void bark()
7. {System.out.println("barking...");}
8. }
9. class BabyDog extends Dog{
10. void weep()
11. {System.out.println("weeping...");}
12. }
13. class TestInheritance2{
14. public static void main(String args[]){
15. BabyDog d=new BabyDog();
16. d.weep();
17. d.bark();
18. d.eat();
19. }}

Output:

weeping...
barking...
eating...

Hierarchical Inheritance Example


When two or more classes inherits a single class, it is known as hierarchical
inheritance.

In the example given below, Dog and Cat classes inherits the Animal class, so there is
hierarchical inheritance.
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class Cat extends Animal{
8. void meow(){System.out.println("meowing...");}
9. }
10. class TestInheritance3{
11. public static void main(String args[]){
12. Cat c=new Cat();
13. c.meow();
14. c.eat();
15. //c.bark();//C.T.Error
16. }}

Output:

meowing...
eating...

Q) Why multiple inheritance is not supported in java?


To reduce the complexity and simplify the language, multiple inheritance is not
supported in java.

Consider a scenario where A, B, and C are three classes. The C class inherits A and B
classes. If A and B classes have the same method and you call it from child class
object, there will be ambiguity to call the method of A or B class.

Since compile-time errors are better than runtime errors, Java renders compile-time
error if you inherit 2 classes. So whether you have same method or different, there
will be compile time error.

1. class A{
2. void msg(){System.out.println("Hello");}
3. }
4. class B{
5. void msg(){System.out.println("Welcome");}
6. }
7. class C extends A,B{//suppose if it were
8.
9. public static void main(String args[]){
10. C obj=new C();
11. obj.msg();//Now which msg() method would be invoked?
12. }
13. }
Compile Time Error
Abstract class in Java
Points to Remember

o An abstract class must be declared with an abstract keyword.


o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of the
method.

Example of abstract class

1. abstract class A{}

Abstract Method in Java


A method which is declared as abstract and does not have implementation is known
as an abstract method.

Example of abstract method

1. abstract void printStatus();//no method body and abstract

Example of Abstract class that has an abstract method


In this example, Bike is an abstract class that contains only one abstract method run.
Its implementation is provided by the Honda class.

1. abstract class Bike{


2. abstract void run();
3. }
4. class Honda4 extends Bike{
5. void run(){System.out.println("running safely");}
6. public static void main(String args[]){
7. Bike obj = new Honda4();
8. obj.run();
9. }
10. }
running safely

Understanding the real scenario of Abstract class


In this example, Shape is the abstract class, and its implementation is provided by the
Rectangle and Circle classes.

Mostly, we don't know about the implementation class (which is hidden to the end
user), and an object of the implementation class is provided by the factory method.

• A factory method is a method that returns the instance of the class.

In this example, if you create the instance of Rectangle class, draw() method of
Rectangle class will be invoked.

File: TestAbstraction1.java

1. abstract class Shape{


2. abstract void draw();
3. }
4. //In real scenario, implementation is provided by others i.e. unknown by end user
5. class Rectangle extends Shape{
6. void draw(){System.out.println("drawing rectangle");}
7. }
8. class Circle1 extends Shape{
9. void draw(){System.out.println("drawing circle");}
10. }
11. //In real scenario, method is called by programmer or user
12. class TestAbstraction1{
13. public static void main(String args[]){
14. Shape s=new Circle1();//In a real scenario, object is provided through method, e.g., getShape
() method
15. s.draw();
16. }
17. }
drawing circle

Abstract class having constructor, data member and


methods
An abstract class can have a data member, abstract method, method body (non-
abstract method), constructor, and even main() method.

1. //Example of an abstract class that has abstract and non-abstract methods


2. abstract class Bike{
3. Bike(){System.out.println("bike is created");}
4. abstract void run();
5. void changeGear(){System.out.println("gear changed");}
6. }
7. //Creating a Child class which inherits Abstract class
8. class Honda extends Bike{
9. void run(){System.out.println("running safely..");}
10. }
11. //Creating a Test class which calls abstract and non-abstract methods
12. class TestAbstraction2{
13. public static void main(String args[]){
14. Bike obj = new Honda();
15. obj.run();
16. obj.changeGear();
17. }
18. }
bike is created
running safely..
gear changed
Rule: If there is an abstract method in a class, that class must be abstract.

1. class Bike12{
2. abstract void run();
3. }
compile time error

Rule: If you are extending an abstract class that has an abstract method, you must
either provide the implementation of the method or make this class abstract.

Method Overriding in Java


• If subclass (child class) has the same method as declared in the parent class, it
is known as method overriding in Java.
• If a subclass provides the specific implementation of the method that has
been declared by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding

o Method overriding is used to provide the specific implementation of a method which


is already provided by its superclass.
o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding

1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).

Example of method overriding


In this example, we have defined the run method in the subclass as defined in the
parent class but it has some specific implementation. The name and parameter of the
method are the same, and there is IS-A relationship between the classes, so there is
method overriding.

1. //Java Program to illustrate the use of Java Method Overriding


2. //Creating a parent class.
3. class Vehicle{
4. //defining a method
5. void run()
6. {System.out.println("Vehicle is running");}
7. }
8. //Creating a child class
9. class Bike2 extends Vehicle{
10. //defining the same method as in the parent class
11. void run()
12. {System.out.println("Bike is running safely");}
13.
14. public static void main(String args[]){
15. Bike2 obj = new Bike2();//creating object
16. obj.run();//calling method
17. }
18. }

Output:

Bike is running safely

Can we override static method?


No, a static method cannot be overridden. It can be proved by runtime
polymorphism.

Why can we not override static method?


It is because the static method is bound with class whereas instance method is
bound with an object. Static belongs to the class area, and an instance belongs to the
heap area.

Can we override java main method?


No, because the main is a static method.
Interface in Java
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


• There can be only abstract methods in the Java interface, not method body. It is used to
achieve abstraction and multiple inheritance in Java
• In other words, you can say that interfaces can have abstract methods and variables.
It cannot have a method body.

• Java Interface also represents the IS-A relationship.

It cannot be instantiated just like the abstract class.

Since Java 8, we can have default and static methods in an interface.

Since Java 9, we can have private methods in an interface.

Why use Java interface?


There are mainly three reasons to use interface. They are given below.

o It is used to achieve abstraction.


o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.

How to declare an interface?


An interface is declared by using the interface keyword. It provides total abstraction;
means all the methods in an interface are declared with the empty body, and all the
fields are public, static and final by default. A class that implements an interface must
implement all the methods declared in the interface.

Syntax:

1. interface <interface_name>{
2. // declare constant fields
3. // declare methods that abstract
4. // by default.
5. }
The relationship between classes and interfaces
As shown in the figure given below, a class extends another class, an interface
extends another interface, but a class implements an interface.

Java Interface Example


In this example, the Printable interface has only one method, and its implementation
is provided in the A6 class.

1. interface printable{
2. void print();
3. }
4. class A6 implements printable{
5. public void print(){System.out.println("Hello");}
6.
7. public static void main(String args[]){
8. A6 obj = new A6();
9. obj.print();
10. }
11. }

Output:

Hello

Java Interface Example: Drawable


In this example, the Drawable interface has only one method.

Its implementation is provided by Rectangle and Circle classes.


In a real scenario, an interface is defined by someone else, but its implementation is
provided by different implementation providers.

Moreover, it is used by someone else.

The implementation part is hidden by the user who uses the interface.

1. //Interface declaration: by first user


2. interface Drawable{
3. void draw();
4. }
5. //Implementation: by second user
6. class Rectangle implements Drawable{
7. public void draw(){System.out.println("drawing rectangle");}
8. }
9. class Circle implements Drawable{
10. public void draw(){System.out.println("drawing circle");}
11. }
12. //Using interface: by third user
13. class TestInterface1{
14. public static void main(String args[]){
15. Drawable d=new Circle();//In real scenario, object is provided by method e.g. getDrawable()
16. d.draw();
17. }}

Output:

drawing circle

Multiple inheritance in Java by interface


If a class implements multiple interfaces, or an interface extends multiple interfaces, it
is known as multiple inheritance.
1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void show();
6. }
7. class A7 implements Printable,Showable{
8. public void print(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10.
11. public static void main(String args[]){
12. A7 obj = new A7();
13. obj.print();
14. obj.show();
15. }
16. }

Output:Hello
Welcome

Interface inheritance
A class implements an interface, but one interface extends another interface.

1. interface Printable{
2. void print();
3. }
4. interface Showable extends Printable{
5. void show();
6. }
7. class TestInterface4 implements Showable{
8. public void print(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10. public static void main(String args[]){
11. TestInterface4 obj = new TestInterface4();
12. obj.print();
13. obj.show();
14. }
15. }

Output:

Hello
Welcome

Difference between abstract class and


interface
• Abstract class and interface both are used to achieve abstraction where we
can declare the abstract methods.
• Abstract class and interface both can't be instantiated.
• But there are many differences between abstract class and interface that are
given below.

Abstract class Interface

1) Abstract class can have abstract and Interface can have only abstract methods.
non-abstract methods. Since Java 8, it can have default and static
methods also.

2) Abstract class doesn't support Interface supports multiple inheritance.


multiple inheritance.

3) Abstract class can have final, non- Interface has only static and final
final, static and non-static variables. variables.

4) Abstract class can provide the Interface can't provide the


implementation of interface. implementation of abstract class.

5) The abstract keyword is used to The interface keyword is used to declare


declare abstract class. interface.

6) An abstract class can extend another An interface can extend another Java
Java class and implement multiple Java interface only.
interfaces.

7) An abstract class can be extended An interface can be implemented using


using keyword "extends". keyword "implements".

8) A Java abstract class can have class Members of a Java interface are public by
members like private, protected, etc. default.

9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface


achieves fully abstraction (100%).

Example of abstract class and interface in Java


Let's see a simple example where we are using interface and abstract class both.

//Creating interface that has 4 methods


1. interface A{
2. void a();//bydefault, public and abstract
3. void b();
4. void c();
5. void d();
6. }
7. //Creating abstract class that provides the implementation of one method of
A interface
8. abstract class B implements A{
9. public void c(){System.out.println("I am C");}
10. }
11.
12. //Creating subclass of abstract class, now we need to provide the implementat
ion of rest of the methods
13. class M extends B{
14. public void a(){System.out.println("I am a");}
15. public void b(){System.out.println("I am b");}
16. public void d(){System.out.println("I am d");}
17. }
18. //Creating a test class that calls the methods of A interface
19. class Test5{
20. public static void main(String args[]){
21. A a=new M();
22. a.a();
23. a.b();
24. a.c();
25. a.d();
26. }}

Output:

I am a
I am b
I am c
I am d

Java Package
A java package is a group of similar types of classes, interfaces and sub-packages.

Package in java can be categorized in two form, built-in package and user-defined
package.

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

Advantage of Java Package


1) Java package is used to categorize the classes and interfaces so that they can be
easily maintained.

2) Java package provides access protection.

3) Java package removes naming collision.


Simple example of java package
The package keyword is used to create a package in java.

1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }

How to compile java package


If you are not using any IDE, you need to follow the syntax given below:

1. javac -d directory javafilename

For example

1. javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You can
use any directory name like /home (in case of Linux), d:/abc (in case of windows) etc.
If you want to keep the package within the same directory, you can use . (dot).

How to run java package program


You need to use fully qualified name e.g. mypack.Simple etc to run the class.

To Compile: javac -d . Simple.java

To Run: java mypack.Simple

Output:Welcome to package

The -d is a switch that tells the compiler where to put the class file i.e. it represents
destination. The . represents the current folder.

How to access 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) Using packagename.*
If you use package.* then all the classes and interfaces of this 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.

Example of package that import the packagename.*


1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }

1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10. }
Output:Hello

2) Using packagename.classname
If you import package.classname then only declared class of this package will be
accessible.

Example of package by import package.classname

1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }

//save by B.java
1. package mypack;
2. import pack.A;
3.
4. class B{
5. public static void main(String args[]){
6. A obj = new A();
7. obj.msg();
8. }
9. }
Output:Hello

3) Using fully qualified name


If you use fully qualified name then only declared class of this package will be
accessible.

Now there is no need to import.

But you need to use fully qualified name every time when you are accessing the class
or interface.

It is generally used when two packages have same class name e.g. java.util and
java.sql packages contain Date class.

Example of package by import fully qualified name

1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }

//save by B.java
1. package mypack;
2. class B{
3. public static void main(String args[]){
4. pack.A obj = new pack.A();//using fully qualified name
5. obj.msg();
6. }
7. }
Output:Hello

Note: If you import a package, subpackages will not be imported.


If you import a package, all the classes and interface of that package will be imported
excluding the classes and interfaces of the subpackages. Hence, you need to import
the subpackage as well.

Note: Sequence of the program must be package then import then class.

Subpackage in java
• Package inside the package is called the subpackage.
• It should be created to categorize the package further.

Let's take an example, Sun Microsystem has definded a package named java that
contains many classes like System, String, Reader, Writer, Socket etc.

These classes represent a particular group e.g. Reader and Writer classes are for
Input/Output operation,

Socket and ServerSocket classes are for networking etc and so on.

So, Sun has subcategorized the java package into subpackages such as lang, net, io
etc. and put the Input/Output related classes in io package, Server and ServerSocket
classes in net packages and so on.

The standard of defining package is domain.company.package e.g. com.vignan.bean or


org.sssit.dao.

Example of Subpackage
1. package com.vignan.core;
2. class Simple{
3. public static void main(String args[]){
4. System.out.println("Hello subpackage");
5. }
6. }
To Compile: javac -d . Simple.java

To Run: java com.vignan.core.Simple

Output:Hello subpackage

What is Exception in Java?

• The Exception Handling in Java is one of the


powerful mechanisms to handle the runtime errors so that the
normal flow of the application can be maintained.
• Dictionary Meaning: Exception is an abnormal condition.
• In Java, an exception is an event that disrupts the normal flow of
the program.
• It is an object which is thrown at runtime.

What is Exception Handling?

• Exception Handling is a mechanism to handle runtime errors such


as
• ClassNotFoundException,
• IOException,
• SQLException,
• RemoteException, etc.

Advantage of Exception Handling


• The core advantage of exception handling is to maintain the
normal flow of the application.
• An exception normally disrupts the normal flow of the application;
that is why we need to handle exceptions. Let's consider a
scenario:

1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;

Suppose there are 10 statements in a Java program and an exception


occurs at statement 5; the rest of the code will not be executed, i.e.,
statements 6 to 10 will not be executed. However, when we perform
exception handling, the rest of the statements will be executed. That is
why we use exception handling in Java.

Hierarchy of Java Exception classes

The java.lang.Throwable class is the root class of Java Exception


hierarchy inherited by two subclasses: Exception and Error.

The hierarchy of Java Exception classes is given below:


Types of Java Exceptions

There are mainly two types of exceptions: checked and unchecked.

An error is considered as the unchecked exception. However, according


to Oracle, there are three types of exceptions namely:

1. Checked Exception
2. Unchecked Exception
3. Error

Difference between Checked and Unchecked


Exceptions

1) Checked Exception
The classes that directly inherit the Throwable class except
RuntimeException and Error are known as checked exceptions.

For example, IOException, SQLException, etc.

Checked exceptions are checked at compile-time.

2) Unchecked Exception

The classes that inherit the RuntimeException are known as unchecked


exceptions.

For example, ArithmeticException, NullPointerException,


ArrayIndexOutOfBoundsException, etc.

Unchecked exceptions are not checked at compile-time, but they are


checked at runtime.

3) Error

Error is irrecoverable.

Some examples of errors are OutOfMemoryError, VirtualMachineError,


AssertionError etc.

Java Exception Keywords

Java provides five keywords that are used to handle the exception. The
following table describes each.

Keyword Description
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.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It


specifies that there may occur an exception in the method. It
doesn't throw an exception. It is always used with method
signature.

Common Scenarios of Java Exceptions

There are given some scenarios where unchecked exceptions may


occur. They are as follows:

1) A scenario where ArithmeticException occurs

If we divide any number by zero, there occurs an ArithmeticException.

1. int a=50/0;//ArithmeticException
2) A scenario where NullPointerException occurs

If we have a null value in any variable, performing any operation on the


variable throws a NullPointerException.

1. String s=null;
2. System.out.println(s.length());//NullPointerException

3) A scenario where NumberFormatException occurs

If the formatting of any variable or number is mismatched, it may result


into NumberFormatException. Suppose we have a string variable that
has characters; converting this variable into digit will cause
NumberFormatException.

1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException

4) A scenario where ArrayIndexOutOfBoundsException occurs

When an array exceeds to it's size, the


ArrayIndexOutOfBoundsException occurs. there may be other reasons
to occur ArrayIndexOutOfBoundsException. Consider the following
statements.

1. int a[]=new int[5];


2. a[10]=50; //ArrayIndexOutOfBoundsException
Java try block

• Java try block is used to enclose the code that might throw an
exception.
• It must be used within the method.
• If an exception occurs at the particular statement in the try block,
the rest of the block code will not execute.
• So, it is recommended not to keep the code in try block that will not
throw an exception.
• Java try block must be followed by either catch or finally block.

Syntax of Java try-catch

1. try{
2. //code that may throw an exception
3. }catch(Exception_class_Name ref){}

Syntax of try-finally block

1. try{
2. //code that may throw an exception
3. }finally{}

Java catch block

Java catch block is used to handle the Exception by declaring the type of
exception within the parameter. The declared exception must be the
parent class exception( i.e., Exception) or the generated exception type.
However, the good approach is to declare the generated type of
exception.
The catch block must be used after the try block only. You can use
multiple catch block with a single try block.

Internal Working of Java try-catch block

The JVM firstly checks whether the exception is handled or not. If


exception is not handled, JVM provides a default exception handler that
performs the following tasks:

o Prints out exception description.


o Prints the stack trace (Hierarchy of methods where the exception
occurred).
o Causes the program to terminate.

But if the application programmer handles the exception, the normal flow
of the application is maintained, i.e., rest of the code is executed.
Problem without exception handling

Let's try to understand the problem if we don't use a try-catch block.

Example 1

TryCatchExample1.java

1. public class TryCatchExample1 {


2.
3. public static void main(String[] args) {
4.
5. int data=50/0; //may throw exception
6.
7. System.out.println("rest of the code");
8.
9. }
10.
11. }

Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero

As displayed in the above example, the rest of the code is not executed
(in such case, the rest of the code statement is not printed).

There might be 100 lines of code after the exception. If the exception is
not handled, all the code below the exception won't be executed.

Solution by exception handling


Let's see the solution of the above problem by a java try-catch block.

Example 2

TryCatchExample2.java

1. public class TryCatchExample2 {


2.
3. public static void main(String[] args) {
4. try
5. {
6. int data=50/0; //may throw exception
7. }
8. //handling the exception
9. catch(ArithmeticException e)
10. {
11. System.out.println(e);
12. }
13. System.out.println("rest of the code");
14. }
15.
16. }

Output:

java.lang.ArithmeticException: / by zero
rest of the code

As displayed in the above example, the rest of the code is executed,


i.e., the rest of the code statement is printed.
Example 3

In this example, we also kept the code in a try block that will not throw
an exception.

TryCatchExample3.java

1. public class TryCatchExample3 {


2.
3. public static void main(String[] args) {
4. try
5. {
6. int data=50/0; //may throw exception
7. // if exception occurs, the remaining statement will
not exceute
8. System.out.println("rest of the code");
9. }
10. // handling the exception
11. catch(ArithmeticException e)
12. {
13. System.out.println(e);
14. }
15.
16. }
17.
18. }

Output:

java.lang.ArithmeticException: / by zero
Here, we can see that if an exception occurs in the try block, the rest of
the block code will not execute.

Example 4

Here, we handle the exception using the parent class exception.

TryCatchExample4.java

1. public class TryCatchExample4 {


2.
3. public static void main(String[] args) {
4. try
5. {
6. int data=50/0; //may throw exception
7. }
8. // handling the exception by using Exception class
9. catch(Exception e)
10. {
11. System.out.println(e);
12. }
13. System.out.println("rest of the code");
14. }
15.
16. }

Output:

java.lang.ArithmeticException: / by zero
rest of the code
Example 5

Let's see an example to print a custom message on exception.

TryCatchExample5.java

1. public class TryCatchExample5 {


2.
3. public static void main(String[] args) {
4. try
5. {
6. int data=50/0; //may throw exception
7. }
8. // handling the exception
9. catch(Exception e)
10. {
11. // displaying the custom message
12. System.out.println("Can't divided by zero");
13. }
14. }
15.
16. }

Output:

Can't divided by zero

Example 6

Let's see an example to resolve the exception in a catch block.

TryCatchExample6.java
1. public class TryCatchExample6 {
2.
3. public static void main(String[] args) {
4. int i=50;
5. int j=0;
6. int data;
7. try
8. {
9. data=i/j; //may throw exception
10. }
11. // handling the exception
12. catch(Exception e)
13. {
14. // resolving the exception in catch block
15. System.out.println(i/(j+2));
16. }
17. }
18. }

Output:

25

Example 7

In this example, along with try block, we also enclose exception code in
a catch block.

TryCatchExample7.java

1. public class TryCatchExample7 {


2.
3. public static void main(String[] args) {
4.
5. try
6. {
7. int data1=50/0; //may throw exception
8.
9. }
10. // handling the exception
11. catch(Exception e)
12. {
13. // generating the exception in catch block
14. int data2=50/0; //may throw exception
15.
16. }
17. System.out.println("rest of the code");
18. }
19. }

Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero

Here, we can see that the catch block didn't contain the exception code.
So, enclose exception code within a try block and use catch block only
to handle the exceptions.

Example 8
In this example, we handle the generated exception (Arithmetic
Exception) with a different type of exception class
(ArrayIndexOutOfBoundsException).

TryCatchExample8.java

1. public class TryCatchExample8 {


2.
3. public static void main(String[] args) {
4. try
5. {
6. int data=50/0; //may throw exception
7.
8. }
9. // try to handle the ArithmeticException using ArrayIndexOu
tOfBoundsException
10. catch(ArrayIndexOutOfBoundsException e)
11. {
12. System.out.println(e);
13. }
14. System.out.println("rest of the code");
15. }
16.
17. }

Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero


Java Catch Multiple Exceptions

Java Multi-catch block

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

Points to remember

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

Flowchart of Multi-catch Block

Example 1
Let's see a simple example of java multi-catch block.

MultipleCatchBlock1.java

1. public class MultipleCatchBlock1 {


2.
3. public static void main(String[] args) {
4.
5. try{
6. int a[]=new int[5];
7. a[5]=30/0;
8. }
9. catch(ArithmeticException e)
10. {
11. System.out.println("Arithmetic Exception occurs")
;
12. }
13. catch(ArrayIndexOutOfBoundsException e)
14. {
15. System.out.println("ArrayIndexOutOfBounds Exc
eption occurs");
16. }
17. catch(Exception e)
18. {
19. System.out.println("Parent Exception occurs");
20. }
21. System.out.println("rest of the code");
22. }
23. }
Output:

Difference between structure and union in Hindi

Keep Watching

Arithmetic Exception occurs


rest of the code

Example 2

MultipleCatchBlock2.java

1. public class MultipleCatchBlock2 {


2.
3. public static void main(String[] args) {
4.
5. try{
6. int a[]=new int[5];
7.
8. System.out.println(a[10]);
9. }
10. catch(ArithmeticException e)
11. {
12. System.out.println("Arithmetic Exception occurs")
;
13. }
14. catch(ArrayIndexOutOfBoundsException e)
15. {
16. System.out.println("ArrayIndexOutOfBounds Exc
eption occurs");
17. }
18. catch(Exception e)
19. {
20. System.out.println("Parent Exception occurs");
21. }
22. System.out.println("rest of the code");
23. }
24. }

Output:

ArrayIndexOutOfBounds Exception occurs


rest of the code

Java Nested try block


In Java, using a try block inside another try block is permitted. It is called
as nested try block. Every statement that we enter a statement in try
block, context of that exception is pushed onto the stack.

For example, the inner try block can be used to


handle ArrayIndexOutOfBoundsException while the outer try
block can handle the ArithemeticException (division by zero).

Why use nested try block

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.
Syntax:

1. ....
2. //main try block
3. try
4. {
5. statement 1;
6. statement 2;
7. //try catch block within another try block
8. try
9. {
10. statement 3;
11. statement 4;
12. //try catch block within nested try block
13. try
14. {
15. statement 5;
16. statement 6;
17. }
18. catch(Exception e2)
19. {
20. //exception message
21. }
22.
23. }
24. catch(Exception e1)
25. {
26. //exception message
27. }
28. }
29. //catch block of parent (outer) try block
30. catch(Exception e3)
31. {
32. //exception message
33. }
34. ....
Java Nested try Example

Example 1

Let's see an example where we place a try block within another try block
for two different exceptions.

NestedTryBlock.java

1. public class NestedTryBlock{


2. public static void main(String args[]){
3. //outer try block
4. try{
5. //inner try block 1
6. try{
7. System.out.println("going to divide by 0");
8. int b =39/0;
9. }
10. //catch block of inner try block 1
11. catch(ArithmeticException e)
12. {
13. System.out.println(e);
14. }
15.
16.
17. //inner try block 2
18. try{
19. int a[]=new int[5];
20.
21. //assigning the value out of array bounds
22. a[5]=4;
23. }
24.
25. //catch block of inner try block 2
26. catch(ArrayIndexOutOfBoundsException e)
27. {
28. System.out.println(e);
29. }
30.
31.
32. System.out.println("other statement");
33. }
34. //catch block of outer try block
35. catch(Exception e)
36. {
37. System.out.println("handled the exception (outer catch)");
38. }
39.
40. System.out.println("normal flow..");
41. }
42. }

Output:
When any try block does not have a catch block for a particular
exception, then the catch block of the outer (parent) try block are
checked for that exception, and if it matches, the catch block of outer try
block is executed.

If none of the catch block specified in the code is unable to handle the
exception, then the Java runtime system will handle the exception. Then
it displays the system generated message for that exception.

Java finally block


Java finally block is a block used to execute important code such as
closing the connection, etc.

Java finally block is always executed whether an exception is handled or


not. Therefore, it contains all the necessary statements that need to be
printed regardless of the exception occurs or not.

The finally block follows the try-catch block.

Flowchart of finally block


Note: If you don't handle the exception, before terminating the
program, JVM executes finally block (if any).

Why use Java finally block?

o finally block in Java can be used to put "cleanup" code such as closing
a file, closing connection, etc.
o The important statements to be printed can be placed in the finally
block.

Usage of Java finally

Let's see the different cases where Java finally block can be used.
Case 1: When an exception does not occur

Let's see the below example where the Java program does not throw
any exception, and the finally block is executed after the try block.

TestFinallyBlock.java

1. class TestFinallyBlock {
2. public static void main(String args[]){
3. try{
4. //below code do not throw any exception
5. int data=25/5;
6. System.out.println(data);
7. }
8. //catch won't be executed
9. catch(NullPointerException e){
10. System.out.println(e);
11. }
12. //executed regardless of exception occurred or not
13. finally {
14. System.out.println("finally block is always executed");
15. }
16.
17. System.out.println("rest of phe code...");
18. }
19. }

Output:
Example:

Let's see the following example where the Java code throws an
exception and the catch block handles the exception. Later the finally
block is executed after the try-catch block. Further, the rest of the code
is also executed normally.

TestFinallyBlock2.java

1. public class TestFinallyBlock2{


2. public static void main(String args[]){
3.
4. try {
5.
6. System.out.println("Inside try block");
7.
8. //below code throws divide by zero exception
9. int data=25/0;
10. System.out.println(data);
11. }
12.
13. //handles the Arithmetic Exception / Divide by zero excep
tion
14. catch(ArithmeticException e){
15. System.out.println("Exception handled");
16. System.out.println(e);
17. }
18.
19. //executes regardless of exception occured or not
20. finally {
21. System.out.println("finally block is always executed");
22. }
23.
24. System.out.println("rest of the code...");
25. }
26. }

Output:

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 the program exits (either
by calling System.exit() or by causing a fatal error that causes the
process to abort).

Java throw Exception


In Java, exceptions allows us to write good quality codes where the errors are
checked at the compile time instead of runtime and we can create custom exceptions
making the code recovery and debugging easier.
Java 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.
• These exceptions may be related to user inputs, server, etc.
• We can throw either checked or unchecked exceptions in Java by throw
keyword. It is mainly used to throw a custom exception.
• We can also define our own set of conditions and throw an exception
explicitly using throw keyword.
• For example, we can throw ArithmeticException if we divide a number by
another number. Here, we just need to set the condition and throw exception
using throw keyword.

The syntax of the Java throw keyword is given below.

throw Instance i.e.,

1. throw new exception_class("error message");

Let's see the example of throw IOException.

1. throw new IOException("sorry device error");

Where the Instance must be of type Throwable or subclass of Throwable. For


example, Exception is the sub class of Throwable and the user-defined exceptions
usually extend the Exception class.

Java throw keyword Example


Example 1: Throwing Unchecked Exception
In this example, we have created a method named validate() that accepts an integer
as a parameter. If the age is less than 18, we are throwing the ArithmeticException
otherwise print a message welcome to vote.

TestThrow1.java

In this example, we have created the validate method that takes integer value as a
parameter. If the age is less than 18, we are throwing the ArithmeticException
otherwise print a message welcome to vote.

1. public class TestThrow1 {


2. //function to check if person is eligible to vote or not
3. public static void validate(int age) {
4. if(age<18) {
5. //throw Arithmetic exception if not eligible to vote
6. throw new ArithmeticException("Person is not eligible to vote");
7. }
8. else {
9. System.out.println("Person is eligible to vote!!");
10. }
11. }
12. //main method
13. public static void main(String args[]){
14. //calling the function
15. validate(13);
16. System.out.println("rest of the code...");
17. }
18. }

Output:

The above code throw an unchecked exception. Similarly, we can also throw
unchecked and user defined exceptions.

Note: If we throw unchecked exception from a method, it is must to handle the exception
or declare in throws clause.

If we throw a checked exception using throw keyword, it is must to handle the


exception using catch block or the method must declare it using throws declaration.
Example 2: Throwing User-defined Exception
exception is everything else under the Throwable class.

TestThrow3.java

1. // class represents user-defined exception


2. class UserDefinedException extends Exception
3. {
4. public UserDefinedException(String str)
5. {
6. // Calling constructor of parent Exception
7. super(str);
8. }
9. }
10. // Class that uses above MyException
11. public class TestThrow3
12. {
13. public static void main(String args[])
14. {
15. try
16. {
17. // throw an object of user defined exception
18. throw new UserDefinedException("This is user-defined exception");
19. }
20. catch (UserDefinedException ude)
21. {
22. System.out.println("Caught the exception");
23. // Print the message from MyException object
24. System.out.println(ude.getMessage());
25. }
26. }
27. }

Output:

Java 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
the normal flow of the program can be maintained.
• 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.

Syntax of Java throws

1. return_type method_name() throws exception_class_name{


2. //method code
3. }

Which exception should be declared?


Ans: Checked exception only, because:

o unchecked exception: under our control so we can correct our code.


o error: beyond our control. For example, we are unable to do anything if there
occurs VirtualMachineError or StackOverflowError.

Advantage of Java throws keyword


Now Checked Exception can be propagated (forwarded in call stack).

It provides information to the caller of the method about the exception.


Java throws Example
Let's see the example of Java throws clause which describes that checked exceptions
can be propagated by throws keyword.

Testthrows1.java

1. import java.io.IOException;
2. class Testthrows1{
3. void m()throws IOException{
4. throw new IOException("device error");//checked exception
5. }
6. void n()throws IOException{
7. m();
8. }
9. void p(){
10. try{
11. n();
12. }catch(Exception e){System.out.println("exception handled");}
13. }
14. public static void main(String args[]){
15. Testthrows1 obj=new Testthrows1();
16. obj.p();
17. System.out.println("normal flow...");
18. }
19. }

Output:

exception handled
normal flow...

Rule: If we are calling a method that declares an exception, we must either caught or
declare the exception.

There are two cases:

1. Case 1: We have caught the exception i.e. we have handled the exception using
try/catch block.
2. Case 2: We have declared the exception i.e. specified throws keyword with the
method.

Case 1: Handle Exception Using try-catch block


In case we handle the exception, the code will be executed fine whether exception
occurs during the program or not.

Testthrows2.java

1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. throw new IOException("device error");
5. }
6. }
7. public class Testthrows2{
8. public static void main(String args[]){
9. try{
10. M m=new M();
11. m.method();
12. }catch(Exception e){System.out.println("exception handled");}
13.
14. System.out.println("normal flow...");
15. }
16. }

Output:

exception handled
normal flow...

Case 2: Declare Exception

o In case we declare the exception, if exception does not occur, the code will be
executed fine.
o In case we declare the exception and the exception occurs, it will be thrown at
runtime because throws does not handle the exception.

Let's see examples for both the scenario.


A) If exception does not occur

Testthrows3.java

1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. System.out.println("device operation performed");
5. }
6. }
7. class Testthrows3{
8. public static void main(String args[])throws IOException{//declare exception
9. M m=new M();
10. m.method();
11.
12. System.out.println("normal flow...");
13. }
14. }

Output:

device operation performed


normal flow...

B) If exception occurs

Testthrows4.java

1. import java.io.*;
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. m.method();
11.
12. System.out.println("normal flow...");
13. }
14. }

Output:

Assertion:
• 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:

1. assert expression;

and second way is:

1. assert expression1 : expression2;

Simple Example of Assertion in java:

1. import java.util.Scanner;
2.
3. class AssertionExample{
4. public static void main( String args[] ){
5.
6. Scanner scanner = new Scanner( System.in );
7. System.out.print("Enter ur age ");
8.
9. int value = scanner.nextInt();
10. assert value>=18:" Not valid";
11.
12. System.out.println("value is "+value);
13. }
14. }
15.
16.
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 AssertionExample.java

Run it by: java -ea AssertionExample

Output: Enter ur age 11


Exception in thread "main" java.lang.AssertionError: Not valid

Where not to use Assertion:


There are some situations where assertion should be avoid to use. They are:

1. According to Sun Specification, assertion should not be used to check arguments in


the public methods because it should result in appropriate runtime exception e.g.
IllegalArgumentException, NullPointerException etc.
2. Do not use assertion, if you don't want any error in any situation.

You might also like