Government Polytechnic Mumbai Department Of Information Technology
Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the properties
and behaviors of a parent object. It is an important part of OOPs
(Object Oriented programming system).
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
● For Method Overriding
(so runtime polymorphism
can be achieved).
● For Code Reusability.
Terms used in Inheritance
● Class: A class is a group of objects which have common properties. It is a
template or blueprint from which objects are created.
● 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.
● 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.
● 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.
Prof. Namrata A. Wankhade 1 Java Programming
Government Polytechnic Mumbai Department Of Information Technology
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{
5. int bonus=10000;
6. public static void main(String args[]){
7. Programmer p=new Programmer();
8. [Link]("Programmer salary is:"+[Link]);
9. [Link]("Bonus of Programmer is:"+[Link]);
10. }
11. }
Output:
Programmer salary is:40000.0
Bonus of programmer is:10000
Prof. Namrata A. Wankhade 2 Java Programming
Government Polytechnic Mumbai Department Of Information Technology
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. We will learn about interfaces later.
Note: Multiple inheritance is not supported in Java through class.
When one class inherits multiple classes, it is known as multiple inheritance. For
Example:
Prof. Namrata A. Wankhade 3 Java Programming
Government Polytechnic Mumbai Department Of Information Technology
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.
File: [Link]
1. class Animal{
2. void eat(){[Link]("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){[Link]("barking...");}
6. }
7. class TestInheritance{
8. public static void main(String args[]){
9. Dog d=new Dog();
10. [Link]();
11. [Link]();
12. }}
Output:
barking...
eating...
Prof. Namrata A. Wankhade 4 Java Programming
Government Polytechnic Mumbai Department Of Information Technology
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.
File: [Link]
1. class Animal{
2. void eat(){[Link]("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){[Link]("barking...");}
6. }
7. class BabyDog extends Dog{
8. void weep(){[Link]("weeping...");}
9. }
10. class TestInheritance2{
11. public static void main(String args[]){
12. BabyDog d=new BabyDog();
13. [Link]();
14. [Link]();
15. [Link]();
16. }}
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.
File: [Link]
1. class Animal{
2. void eat(){[Link]("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){[Link]("barking...");}
6. }
7. class Cat extends Animal{
Prof. Namrata A. Wankhade 5 Java Programming
Government Polytechnic Mumbai Department Of Information Technology
8. void meow(){[Link]("meowing...");}
9. }
10. class TestInheritance3{
11. public static void main(String args[]){
12. Cat c=new Cat();
13. [Link]();
14. [Link]();
15. //[Link]();//[Link]
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(){[Link]("Hello");}
3. }
4. class B{
5. void msg(){[Link]("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. [Link]();//Now which msg() method would be invoked?
12. }
13. }
Compile Time Error
Prof. Namrata A. Wankhade 6 Java Programming
Government Polytechnic Mumbai Department Of Information Technology
Super Keyword in Java
The super keyword in Java is a reference variable which is used to refer immediate
parent class object.
Whenever you create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference variable.
Usage of Java super Keyword
1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.
Prof. Namrata A. Wankhade 7 Java Programming
Government Polytechnic Mumbai Department Of Information Technology
Dynamic Method Dispatch or Runtime Polymorphism in Java
Method overriding is one of the ways in which Java supports Runtime Polymorphism.
Dynamic method dispatch is the mechanism by which a call to an overridden method is
resolved at run time, rather than compile time.
● When an overridden method is called through a superclass reference, Java
determines which version(superclass/subclasses) of that method is to be
executed based upon the type of the object being referred to at the time the
call occurs. Thus, this determination is made at run time.
● At run-time, it depends on the type of the object being referred to (not the
type of the reference variable) that determines which version of an overridden
method will be executed
● A superclass reference variable can refer to a subclass object. This is also
known as upcasting. Java uses this fact to resolve calls to overridden methods
at run time.
Therefore, if a superclass contains a method that is overridden by a subclass, then when
different types of objects are referred to through a superclass reference variable,
different versions of the method are executed. Here is an example that illustrates
dynamic method dispatch:
Prof. Namrata A. Wankhade 8 Java Programming
Government Polytechnic Mumbai Department Of Information Technology
// A Java program to illustrate Dynamic Method
// Dispatch using hierarchical inheritance
class A
{
void m1()
{
[Link]("Inside A's m1 method");
}
}
class B extends A
{
// overriding m1()
void m1()
{
[Link]("Inside B's m1 method");
}
}
class C extends A
{
// overriding m1()
void m1()
{
[Link]("Inside C's m1 method");
}
}
// Driver class
class Dispatch
{
public static void main(String args[])
{
// object of type A
A a = new A();
// object of type B
B b = new B();
// object of type C
C c = new C();
// obtain a reference of type A
A ref;
Prof. Namrata A. Wankhade 9 Java Programming
Government Polytechnic Mumbai Department Of Information Technology
// ref refers to an A object
ref = a;
// calling A's version of m1()
ref.m1();
// now ref refers to a B object
ref = b;
// calling B's version of m1()
ref.m1();
// now ref refers to a C object
ref = c;
// calling C's version of m1()
ref.m1();
}
}
Output:
Inside A's m1 method
Inside B's m1 method
Inside C's m1 method
Explanation :
The above program creates one superclass called A and it’s two subclasses B and C.
These subclasses overrides m1( ) method.
Inside the main() method in Dispatch class, initially objects of type A, B, and C are
declared.
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
Prof. Namrata A. Wankhade 10 Java Programming
Government Polytechnic Mumbai Department Of Information Technology
1.
Now a reference of type A, called ref, is also declared, initially it will point to null.
A ref; // obtain a reference of type A
2.
Now we are assigning a reference to each type of object (either A’s or B’s or C’s) to ref,
one-by-one, and uses that reference to invoke m1( ). As the output shows, the version of
m1( ) executed is determined by the type of object being referred to at the time
of the call.
ref = a; // r refers to an A object
ref.m1(); // calling A's version of m1()
Prof. Namrata A. Wankhade 11 Java Programming
Government Polytechnic Mumbai Department Of Information Technology
ref = b; // now r refers to a B object
ref.m1(); // calling B's version of m1()
ref = c; // now r refers to a C object
ref.m1(); // calling C's version of m1()
Prof. Namrata A. Wankhade 12 Java Programming
Government Polytechnic Mumbai Department Of Information Technology
3.
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.
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.
● It is used to achieve abstraction.
● By interface, we can support the functionality of multiple inheritance.
● It can be used to achieve loose coupling.
Prof. Namrata A. Wankhade 13 Java Programming
Government Polytechnic Mumbai Department Of Information Technology
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.
3. // declare constant fields
4. // declare methods that abstract
5. // by default.
6. }
Java 8 Interface Improvement
Since Java 8
, interface can have default and static methods which is discussed later.
Internal addition by the compiler
The Java compiler adds public and abstract keywords before the interface method.
Moreover, it adds public, static and final keywords before data members.
Prof. Namrata A. Wankhade 14 Java Programming
Government Polytechnic Mumbai Department Of Information Technology
In other words, Interface fields are public, static and final by default, and the methods
are public and abstract.
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(){[Link]("Hello");}
6.
Prof. Namrata A. Wankhade 15 Java Programming
Government Polytechnic Mumbai Department Of Information Technology
7. public static void main(String args[]){
8. A6 obj = new A6();
9. [Link]();
10. }
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.
File: [Link]
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(){[Link]("drawing rectangle");}
8. }
9. class Circle implements Drawable{
10. public void draw(){[Link]("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. [Link]();
17. }}
Output:
drawing circle
Prof. Namrata A. Wankhade 16 Java Programming
Government Polytechnic Mumbai Department Of Information Technology
Java Interface Example: Bank
Let's see another example of java interface which provides the implementation of Bank
interface.
File: [Link]
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
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple interfaces, it
is known as multiple inheritance.
Prof. Namrata A. Wankhade 17 Java Programming
Government Polytechnic Mumbai Department Of Information Technology
1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void show();
6. }
7. class A7 implements Printable,Showable{
8. public void print(){[Link]("Hello");}
9. public void show(){[Link]("Welcome");}
10.
11. public static void main(String args[]){
12. A7 obj = new A7();
13. [Link]();
14. [Link]();
15. }
Output:Hello
Welcome
Q) Multiple inheritance is not supported through class in java, but it is possible by an
interface, why?
As we have explained in the inheritance chapter, multiple inheritance is not supported
in the case of class
because of ambiguity. However, it is supported in case of an interface because there is
no ambiguity. It is because its implementation is provided by the implementation class.
For example:
1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void print();
6. }
7.
8. class TestInterface3 implements Printable, Showable{
9. public void print(){[Link]("Hello");}
10. public static void main(String args[]){
11. TestInterface3 obj = new TestInterface3();
12. [Link]();
13. }
14. }
Prof. Namrata A. Wankhade 18 Java Programming
Government Polytechnic Mumbai Department Of Information Technology
Output:
Hello
As you can see in the above example, Printable and Showable interface have same
methods but its implementation is provided by class TestTnterface1, so there is no
ambiguity.
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(){[Link]("Hello");}
9. public void show(){[Link]("Welcome");}
10.
11. public static void main(String args[]){
12. TestInterface4 obj = new TestInterface4();
13. [Link]();
14. [Link]();
15. }
16. }
Output:
Hello
Welcome
Prof. Namrata A. Wankhade 19 Java Programming
Government Polytechnic Mumbai Department Of Information Technology
Exception Handling in Java
The Exception Handling in Java is one of the powerful mechanism to handle the
runtime errors so that the normal flow of the application can be maintained.
In this tutorial, we will learn about Java exceptions, it's types, and the difference
between checked and unchecked exceptions.
What is Exception in Java?
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.
Prof. Namrata A. Wankhade 20 Java Programming
Government Polytechnic Mumbai Department Of Information Technology
Do You Know?
● What is the difference between checked and unchecked exceptions?
● What happens behind the code int data=50/0;?
● Why use multiple catch block?
● Is there any possibility when the finally block is not executed?
● What is exception propagation?
● What is the difference between the throw and throws keyword?
● What are the 4 rules for using exception handling with method overriding?
Hierarchy of Java Exception classes
The [Link] 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:
Prof. Namrata A. Wankhade 21 Java Programming
Government Polytechnic Mumbai Department Of Information Technology
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
Prof. Namrata A. Wankhade 22 Java Programming
Government Polytechnic Mumbai Department Of Information Technology
Error is irrecoverable. Some example 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.
Keyw Description
ord
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.
Java Exception Handling Example
Let's see an example of Java Exception Handling in which we are using a try-catch
statement to handle the exception.
[Link]
1. public class JavaExceptionExample{
2. public static void main(String args[]){
3. try{
4. //code that may raise exception
5. int data=100/0;
6. }catch(ArithmeticException e){[Link](e);}
7. //rest code of the program
Prof. Namrata A. Wankhade 23 Java Programming
Government Polytechnic Mumbai Department Of Information Technology
8. [Link]("rest of the code...");
9. }
10. }
Output:
Exception in thread main [Link]:/ by zero
rest of the code...
In the above example, 100/0 raises an ArithmeticException which is handled by a
try-catch block.
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. [Link]([Link]());//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=[Link](s);//NumberFormatException
4) A scenario where ArrayIndexOutOfBoundsException occurs
Prof. Namrata A. Wankhade 24 Java Programming
Government Polytechnic Mumbai Department Of Information Technology
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 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
● At a time only one exception occurs and at a time only one catch block is
executed.
● All catch blocks must be ordered from most specific to most general, i.e. catch for
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.
Prof. Namrata A. Wankhade 25 Java Programming
Government Polytechnic Mumbai Department Of Information Technology
[Link]
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. [Link]("Arithmetic Exception occurs");
12. }
13. catch(ArrayIndexOutOfBoundsException e)
14. {
15. [Link]("ArrayIndexOutOfBounds Exception occurs");
16. }
17. catch(Exception e)
18. {
19. [Link]("Parent Exception occurs");
20. }
21. [Link]("rest of the code");
22. }
23. }
Output:
Arithmetic Exception occurs
rest of the code
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.
Prof. Namrata A. Wankhade 26 Java Programming
Government Polytechnic Mumbai Department Of Information Technology
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 will discuss custom exceptions later in this
section.
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.
[Link]
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. }
Prof. Namrata A. Wankhade 27 Java Programming
Government Polytechnic Mumbai Department Of Information Technology
8. else {
9. [Link]("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. [Link]("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.
[Link]
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);
Prof. Namrata A. Wankhade 28 Java Programming
Government Polytechnic Mumbai Department Of Information Technology
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. [Link]("Caught the exception");
23. // Print the message from MyException object
24. [Link]([Link]());
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. }
Advantage of Java throws keyword
Prof. Namrata A. Wankhade 29 Java Programming
Government Polytechnic Mumbai Department Of Information Technology
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.
[Link]
1. import [Link];
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){[Link]("exception handled");}
13. }
14. public static void main(String args[]){
15. Testthrows1 obj=new Testthrows1();
16. obj.p();
17. [Link]("normal flow...");
18. }
19. }
Output:
exception handled
normal flow...
Prof. Namrata A. Wankhade 30 Java Programming