UNIT 2
INHERITANCE, PACKAGE, INTERFACE AND EXCEPTION
Inheritance: Basics — Using Super — Creating Multilevel
Hierarchy — Constructors — Overriding — Dispatch — Abstract
Class -Packages: Member Access— Importing Packages —
Interfaces: Implementing and Nesting — Applying Interfaces —
Default Interface Methods - Exception Handling: Fundamentals —
Exception Types — Uncaught Exception — Using try and catch—
Multiple catch Clauses — Nested try statements — throw — throws
— finally — Built-in Exception — Creating our own Exception
class — Chained Exception.
2
Introduction
• Error:
– An error defines a reasonable issue that is stopping
the execution of the program.
• Exception:
– powerful mechanism to handle the runtime errors
so that the normal flow of the application can be
maintained.
– It is an event, which occurs during the execution of
a program, that disrupts the normal flow of the
program's Instructions.
Real time Example
Why use Exception Handling?
• Handling the exception is nothing but converting system
error generated message into user friendly error
message.
• Whenever an exception occurs in the java application,
JVM will create an object of appropriate exception of sub
class and generates system error message, these system
generated messages are not understandable by user.
• So need to convert it into user friendly error message.
• You can convert system error message into user friendly
error message by using exception handling feature of
when you divide any number by zero then system generate / by zero so this is
java.
not understandable by user so you can convert this message into user friendly
error message like Don't enter zero for denominator.
Error Exception
Can't be handle. Can be handle.
Can be either checked type or Errors are of unchecked type
unchecked type
Thrown at runtime only, but the Occurs at the runtime of the code
checked exceptions known by the and is not known to the compiler.
compiler and the unchecked are not.
They are defined in They are defined in Java.lang.Error
Java.lang.Exception package. package
Program implementation mistakes Errors are mainly caused because of
cause exceptions. the environment of the program
where it is executing.
Example: Example:
NoSuchMethodError ClassNotFoundException
OutOfMemoryError NumberFormateException
Hierarchy of Exception classes
Type of Exception
• Checked Exception
• Un-Checked Exception
• Error
Checked Exception
• Checked Exception are the exception which checked at
compile-time. These exception are directly sub-class of
java.lang.Exception class.
• Note:
– Checked means checked by compiler so checked
exception are checked at compile-time.
Un-Checked Exception
• Un-Checked Exception are the exception both
identifies or raised at run time. These exception are
directly sub-class of java.lang.RuntimeException class.
• Note:
– In real time application mostly we can handle un-
checked exception.
– Un-checked means not checked by compiler so un-
checked exception are checked at run-time not
compile time.
Checked Exception Un-Checked Exception
checked Exception are un-checked Exception
checked at compile time are checked at run time
e.g.
e.g.
ArithmeticException,
FileNotFoundException,
NullPointerException,
NumberNotFoundExcep
ArrayIndexOutOfBound
tion etc.
sException etc.
Uncaught Exceptions in Java
• In java, assume that, if we do not handle the exceptions in a
program. In this case, when an exception occurs in a particular
function, then Java prints a exception message with the help of
uncaught exception handler.
• The uncaught exceptions are the exceptions that are not caught
by the compiler but automatically caught and handled by the Java
built-in exception handler.
• Java programming language has a very strong exception handling
mechanism. It allows us to handle the exception use the keywords
like try, catch, finally, throw, and throws.
Uncaught Exceptions in Java
• The Division by zero exception is one of the example for uncaught
exceptions. Look at the following code.
Example:
import java.util.Scanner;
public class UncaughtExceptionExample {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
System.out.println("Enter the a and b values: ");
int a = read.nextInt();
int b = read.nextInt();
int c = a / b;
System.out.println(a + "/" + b +" = " + c);
}}
In the above example code, we are not used try and catch blocks, but when the
value of b is zero the division by zero exception occurs and it caught by the
default exception handler.
Handling the Exception
• Use Five keywords for Handling the Exception
– try
– catch
– finally
– throws
– throw
try Syntax for handling the exception
{
// statements causes problem at run time
}
catch(type of exception-1 object-1)
{
// statements provides user friendly error message
}
catch(type of exception-2 object-2)
{
// statements provides user friendly error message
}
finally
{
// statements which will execute compulsory
}
Example without Exception Handling
class ExceptionDemo
{
public static void main(String[] args)
{
int a=10, ans=0;
ans=a/0;
System.out.println("Denominator not be zero");
}}
Example of Exception Handling
class ExceptionDemo
{
public static void main(String[] args)
{
int a=10, ans=0;
try
{
ans=a/0;
}
catch (Exception e)
{
System.out.println("Denominator not be zero");
}
}}
try and catch block
• try block
– Inside try block we write the block of statements
which causes executions at run time in other words
try block always contains problematic statements.
• Important points about try block
– If any exception occurs in try block then CPU controls
comes out to the try block and executes appropriate
catch block.
– After executing appropriate catch block, even
through we use run time statement, CPU control
never goes to try block to execute the rest of the
statements.
– Each and every try block must be immediately
followed by catch block that is no intermediate
statements are allowed between try and catch
block.
– Each and every try block must contains at least one
catch block. But it is highly recommended to write
multiple catch blocks for generating multiple user
friendly error messages.
– One try block can contains another try block that is
nested or inner try block can be possible.
try try
{ {
..... .......
} try
/* Here no other statements {
are allowed .......
between try and catch block }
*/ }
catch()
{
....
}
catch block
• Inside catch block we write the block of statements which
will generates user friendly error messages.
• catch block important points
– Catch block will execute exception occurs in try block.
– You can write multiple catch blocks for generating
multiple user friendly error messages to make your
application strong. You can see below example.
– At a time only one catch block will execute out of
multiple catch blocks.
– in catch block you declare an object of sub class and it
will be internally referenced by JVM.
Multiple catch Clauses
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: Simple example of java multi-catch block
class MultipleCatchBlock1 { catch(Exception e)
public static void main(String[] args) { {
try { System.out.println("Parent
Exception occurs");
int a[]=new int[5];
}
a[5]=30/0; System.out.println("rest of the
} code");
catch(ArithmeticException e) }
{ }
System.out.println("Arithmetic Exception
occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBound
Exception occurs");
} Arithmetic Exception occurs
rest of the code
Example 1: Simple example of java multi-catch block
class MultipleCatchBlock1 { catch(Exception e)
public static void main(String[] args) { {
try { System.out.println("Parent
Exception occurs");
int a[]=new int[5];
}
System.out.println(a[10]); System.out.println("rest of the
} code");
catch(ArithmeticException e) }
{ }
System.out.println("Arithmetic
Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{ System.out.println("ArrayIndexOutOf
Bound Exception occurs");
}
ArrayIndexOutOfBounds Exception occurs
rest of the code
Example 1: Simple example of java multi-catch block
class MultipleCatchBlock1 { catch(Exception e)
public static void main(String[] args) { {
try { System.out.println("Parent Exception
occurs");
int a[]=new int[5];
}
a[5]=30/0; System.out.println("rest of the code");
System.out.println(a[10]); }
} }
catch(ArithmeticException e)
{
System.out.println("Arithmetic
Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{ System.out.println("ArrayIndexOutOf
Bound Exception occurs");
Arithmetic Exception occurs
}
rest of the code
Nested try statements
• 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.
class NestedTryBlock{ try{
public static void main(String args[]){ int a[]=new int[5];
//outer try block //assigning the value out of array bounds
try{ a[5]=4;
//inner try block 1 }
try{ //catch block of inner try block 2
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("going to divide by 0");
System.out.println(e); }
int b =39/0;
System.out.println("other statement");
}
}
//catch block of inner try block 1
//catch block of outer try block
catch(ArithmeticException e) catch(Exception e) {
{ System.out.println("handled the exception
System.out.println(e); (outer catch)"); }
} System.out.println("normal flow..");
//inner try block 2 }}
throw
• The throw keyword is used to explicitly
throw a single exception.
• When an exception is thrown, the flow of
program execution transfers from
the try block to the catch block. We use
the throw keyword within a method.
• Its syntax is:
– throw throwableObject;
Java Throw Example
class Main {
public static void divideByZero()
{
throw new ArithmeticException("Trying to divide by 0");
}
public static void main(String[] args)
{
divideByZero();
}
}
public class TestThrow1 {
//function to check if person is eligible to vote or not
public static void validate(int age) {
if(age<18) {
//throw Arithmetic exception if not eligible to vote
throw new ArithmeticException("Person is not eligible to vote");
}
else {
System.out.println("Person is eligible to vote!!");
}
}
//main method
public static void main(String args[]){
//calling the function
validate(13);
System.out.println("rest of the code...");
}
}
throws
• The throws keyword in Java is used to declare
exceptions that can occur during the execution of a
program.
• For any method that can throw exceptions, it is
mandatory to use the throws keyword to list the
exceptions that can be thrown.
• The throws keyword provides information about the
exceptions to the programmer as well as to the caller
of the method that throws the exceptions.
• The throws keyword is used in a method signature
and declares which exceptions can be thrown from a
method.
• The throws keyword allows exceptions to be
propagated in the call stack.
• When a method declares that it throws an exception, it
is not required to handle the exception.
• The caller of a method that throws exceptions is
required to handle the exceptions (or throw them to
its caller and so on) so that the flow of the program
can be maintained.
• Only checked exceptions are required to be thrown
using the throws keyword.
• Unchecked exceptions don’t need to be thrown or
handled explicitly in code.
Java Throws Example
public void myMethod()
{
try {
// Statements that might throw an
exception
}
catch (ArithmeticException e) {
// Exception handling statements
}
catch (NullPointerException e) {
// Exception handling statements
}}
public void myMethod() throws ArithmeticException,
NullPointerException
{
// Statements that might throw an exception
}
public static void main(String args[]) {
try {
myMethod();
}
catch (ArithmeticException e) {
// Exception handling statements
}
catch (NullPointerException e) {
// Exception handling statements
}}
finally Block in Exception Handling
try
• finally block important {
points ans=a/0;
– Finally block will execute }
compulsory catch (Exception e)
– Writing finally block is {
optional. System.out.println("Denominat
– You can write finally block or not be zero");
for the entire java }
program
finally
– In some of the
circumstances one can {
also write try and catch System.out.println("I am from
block in finally block. finally block");
}
Creating our own Exception class
The Java programming language allow us to create our own
exception classes which are basically subclasses built-in class
Exception.
To create our own exception class simply create a class as a
subclass of built-in Exception class.
We may create constructor in the user-defined exception class and
pass a string to Exception class constructor using super(). We can
use getMessage() method to access the string.
Example 1: User Defined Exception
import java.util.Scanner; import java.util.Scanner;
public class Mainclass { public class Mainclass {
public static void args) { public static void args) {
try {
try {
int a=12;
int a=12; throw new Exception();
} }
catch(Exception e) catch(Exception e)
{ {
Systen.out.printin(e); Systen.out.printin(e);
}
}
System.out.print1n(“No problem");
System.out.print1n(“No problem"); }
}
java.lang.exception
No problem No problem
import java.util.Scanner;
public class Mainclass {
public static void args) {
try {
int a=12;
throw new Exception();
}
catch(ArithmeticException e){
System.out.println(e) ;
}
catch(Exception e)
{
Systen.out.println(e);
}
System.out.print1n(“No problem");
}
java.lang.ArithmeticException: / by Zero
No problem
Example 1: User Defined Exception System.out.println("Congrates! You are
import java.util.Scanner; eligible for vote.");
class NotEligibleException extends }
Exception{
catch(NotEligibleException nee) {
NotEligibleException(String msg){
super(msg); System.out.println(nee.getMessage());
}} } }
class VoterList{ public static void main(String args[]) {
int age;
Scanner input = new
VoterList(int age){
this.age = age; Scanner(System.in);
} System.out.println("Enter your age in
void checkEligibility() {
years: ");
try {
if(age < 18) { int age = input.nextInt();
throw new NotEligibleException("Error: Not VoterList person = new VoterList(age);
eligible for vote due to under age.");
person.checkEligibility();
}
}}
Example 1: User Defined Exception
import java. util. Scanner; import java. util. Scanner;
public class Mainclass { class InvalidException exdends
public static void(String args[]) { Exception{
public class Mainclass {
Scanner obj=new Scanner(System.in);
public static void(String args[]) {
try { Scanner obj=new Scanner(System.in);
int age = obj.nextInt(); try {
} int age = obj.nextInt();
catch(Exception e) if(age<18)
{ { throw new InvalidException( );
}
System.out.println(e) ;
catch(InvalidException e)
} {
} System.out.println(Invalid age) ;
} }
catch(Exception e)
{
System.out.println(e) ;
12
} }}
InvalidException
Example 1: Simple example of java multi-catch block
import java. util. Scanner; catch(InvalidException e)
class InvalidException exdends Exception {
{ System.out.println(Invalid age) ;
public NotVa1idException(String s) }
super(s); catch(Exception e)
public class Mainclass { {
public static void(String args[]) { System.out.println(e) ;
Scanner obj=new Scanner(System.in); } }}
try {
int age = obj.nextInt();
if(age<18)
{
throw new InvalidException(“Your age
should be above 18”);
}
12
java.InValidException: Your age should be above 18
Chained Exception
Definition
• The chained exception feature allows you to
associate another exception with an
exception. This second exception describes
the cause of the first exception.
• This concept was introduced in JDK 1.4.
Example 1
• Imagine a situation in which a method
throws an ArithmeticException because
of an attempt to divide by zero. However,
the actual cause of the problem was that an
I/O error occurred, which caused the divisor
to be set improperly. Although the method
must certainly throw
an ArithmeticException, since that is the
error that occurred, you might also want to
let the calling code know that the
underlying cause was an I/O error.
Example 2:
• Imagine a situation in which a method
throws an NullPointerException
because of a failed attempt to initialize
an object reference. However, the
actual cause of the problem was that
an IOException (I/O exception)
occurred, which caused the object
reference to be initialized improperly
and as a result it becomes null.
Throwable Class
• Throwable class used to handle chained
exceptions.
• Constructors
– Throwable(Throwable cause) – Throwable has a single parameter,
which specifies the actual cause of an Exception.
– Throwable(String desc, Throwable cause) – this constructor accepts
an Exception description with the actual cause of an Exception as
well.
• getCause() method – This method returns the
actual cause associated with the current Exception.
• initCause() method – It sets an underlying cause
with invoking Exception