SlideShare a Scribd company logo
Exception handling and packages.pdf
Using Abstract Classes
 There are situations in which you will want to define a superclass that declares the structure of a given
abstraction without providing a complete implementation of every method.
 That is, sometimes you will want to create a superclass that only defines a generalized form that will be
shared by all of its subclasses, leaving it to each subclass to fill in the details.
 Such a class determines the nature of the methods that the subclasses must implement.
 One way this situation can occur is when a superclass is unable to create a meaningful implementation for a
method.
2
Abstraction in Java
 Abstraction is a process of hiding the implementation details and showing only
functionality to the user.
 Abstraction lets you focus on what the object does instead of how it does it.
 There are two ways to achieve abstraction in java
• Abstract class (0 to 100%)
• Interface (100%)
3
Abstract class in Java
 A class which is declared with the abstract keyword is known as an abstract class.
 It can have abstract and non-abstract methods (method with the body).
 A class which extends an abstract class must implement all the abstract methods in abstract class otherwise
the class should be defined as an abstract class.
 It cannot be instantiated.
Some important points
• An abstract class must be declared with an abstract keyword.
• It can have abstract and non-abstract methods.
• It can have constructors and static methods also.
• It can have final methods which will force the subclass not to change the body of the method.
4
Example of Abstract class that has an abstract method
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run()
{
System.out.println("running safely");
}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
5
One more example of overriding
6
// Using run-time polymorphism.
abstract class Figure {
double dim1;
double dim2;
Figure(double a, double b) {
dim1 = a;
dim2 = b;
}
abstract double area();
}
class Rectangle extends Figure {
Rectangle(double a, double b) {
super(a, b);
}
// override area for rectangle
double area() { // must be override all abstract methods of abstract class
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}
7
class Triangle extends Figure {
Triangle(double a, double b) {
super(a, b);}
double area() {
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;}
}
class FindAreas {
public static void main(String args[]) {
//Figure f = new Figure(10, 10);
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref;
figref = r;
System.out.println("Area is " + figref.area());
figref = t;
System.out.println("Area is " + figref.area());
figref = f;
System.out.println("Area is " + figref.area());
}
}
Understanding the real scenario of Abstract class
 In previous example, Figure is the abstract class, and its implementation is provided by the Rectangle and
Triangle 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. We will learn about the factory method
later.
 In this example, if you create the instance of Rectangle class, draw() method of Rectangle class will be
invoked.
8
One more example
abstract class Figure{
abstract void draw();
}
//In real scenario, implementation is provided by others i.e. unknown by end user
class Rectangle extends Figure{
void draw(){System.out.println("drawing rectangle");}
}
class Triangle extends Figure{
void draw(){System.out.println("drawing Triangle");}
}
//In real scenario, method is called by programmer or user
class TestAbstraction1{
public static void main(String args[]){
Figure f=new Triangle();
//In a real scenario, object is provided through method, e.g., getShape() method
f.draw();
}
}
9
Interface in Java
 An interface in Java is a blueprint of a class.
 All variable in interfaces are implicitly static final and all methods are abstract methods.
 The interface in Java is a mechanism to achieve abstraction. It is used to achieve
abstraction and multiple inheritance in Java.
 It cannot be instantiated just like the abstract class.
10
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.
 A class implements interface while and interface extends other interfaces.
 The Java compiler adds public and abstract keywords before the interface method. Moreover, it adds public,
static and final keywords before data members.
11
The relationship between classes and interfaces
12
How to define interface
 An interface is defined much like a class. This is the general form of an interface:
access interface name {
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
// ...
return-type method-nameN(parameter-list);
13
Here, access is either public or not used. When no access specifier is included,
then default access results, and the interface is only available to other members
of the package in which it is declared. When it is declared as public, the interface
can be used by any other code.
Java Interface Example
14
interface printable
{
void print();
}
class A6 implements printable
{
public void print()
{System.out.println("Hello");
}
public static void main(String args[]){
A6 obj = new A6();
obj.print();
}
}
Java Interface Example: Drawable
15
//Interface declaration: by first user
interface Drawable{
void draw();
}
//Implementation: by second user
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class Circle implements Drawable{
public void draw(){System.out.println("drawing circle");}
}
//Using interface: by third user
class TestInterface1{
public static void main(String args[]){
Drawable d=new Circle();
//In real scenario, object is provided by method e.g. getDrawable()
d.draw();
}
}
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.
Interfaces Can Be Extended
16
// One interface can extend another.
interface A {
void meth1();
void meth2();
}
// B now includes meth1() and meth2() — it adds meth3().
interface B extends A {
void meth3();
}
// This class must implement all of A and B
class MyClass implements B {
public void meth1() {
System.out.println("Implement meth1().");
}
public void meth2() {
System.out.println("Implement meth2().");
}
public void meth3() {
System.out.println("Implement meth3().");
}
}
class IFExtend {
public static void main(String arg[]) {
MyClass ob = new MyClass();
ob.meth1();
ob.meth2();
ob.meth3();
}
Multiple inheritance in Java by interface
 If a class implements multiple interfaces, or an interface extends multiple interfaces, it is
known as multiple inheritance.
17
18
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable
{
public void print(){
System.out.println("Hello");}
public void show(){
System.out.println("Welcome");}
public static void main(String args[]){
A7 obj = new A7();
obj.print();
obj.show();
}
}
Difference between abstract class and interface
19
Abstract class Interface
1) Abstract class can have abstract and non-
abstract methods.
Interface can have only abstract methods. Since Java 8, it
can have default and static methods also.
2) Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance.
3) Abstract class can have final, non-final, static and
non-static variables.
Interface has only static and final variables.
4) Abstract class can provide the implementation of
interface.
Interface can't provide the implementation of abstract
class.
5) The abstract keyword is used to declare abstract class. The interface keyword is used to declare interface.
6) An abstract class can extend another Java class and
implement multiple Java interfaces.
An interface can extend another Java interface only.
7) An abstract class can be extended using keyword
"extends".
An interface can be implemented using keyword
"implements".
8) A Java abstract class can have class members like
private, protected, etc.
Members of a Java interface are public by default.
9)Example:
public abstract class Shape{
public abstract void draw();
}
Example:
public interface Drawable{
void draw();
}
Java Packages
 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.
20
Java package hierarchy
21
Defining a Package
 This is the general form of the package statement:
package pkg;
 For example, the following statement creates a package called MyPackage
containing a class A
package MyPackage;
class A{
void show()
{
System.out.println(“print A”);
}
}
 Java uses file system directories to store packages.
 For example, the .class files for any classes you declare to be part
of MyPackage must be stored in a directory called MyPackage.
22
 More than one file can include the same package statement. The
package statement simply specifies to which package the classes
defined in a file belong.
 Most real-world packages are spread across many files.
 You can create a hierarchy of packages. To do so, simply separate
each package name from the one above it by use of a period.
Syntax
package pkg1[.pkg2[.pkg3]];
Example
package java.awt.image;
23
A Short Package Example
package MyPack;
class Balance {
String name;
double bal;
Balance(String n, double b) {
name = n;
bal = b;}
void show() {
if(bal<0)
System.out.print("—> ");
System.out.println(name + ": $" + bal);}
}
class AccountBalance {
public static void main(String args[]) {
Balance current[] = new Balance[3];
current[0] = new Balance("K. J. Fielding", 123.23);
current[1] = new Balance("Will Tell", 157.02);
current[2] = new Balance("Tom Jackson", -12.33);
for(int i=0; i<3; i++) current[i].show();}
} 24
Package compilation
 Create a directory with the name MyPack in current directory
 Save the file with “AccountBalance.java” in MyPack
 Write following command in current working directory where you have created MyPack to compile the
package
javac MyPackAccountBalance.java
 The above command will create a package MyPack containg two .class files Balance.java and
AccountBalance. Java
 If you don’t want to create MyPack directory then using following command the directory will be created by
command itself within the current directory..
 Save your java file in current directory and execute following command to create the package MyPack
javac –d . AccountBalance.java
25
Running the class inside a package
 Execute the AccountBalance class, using the following command
java MyPack.AccountBalance
 Remember, you will need to be in the directory above MyPack when you execute this
command, or to have your CLASSPATH environmental variable set appropriately.
26
Packages and Member Access
 Classes and packages are both means of encapsulating and containing the name
space and scope of variables and methods.
 Packages act as containers for classes and other subordinate packages.
 Classes act as containers for data and code. The class is Java's smallest unit of
abstraction.
 Java addresses four categories of visibility for class members:
1. Subclasses in the same package
2. Non-subclasses in the same package
3. Subclasses in different packages
4. Classes that are neither in the same package nor subclasses
27
Access Control
28
The three access specifiers, private, public, and protected, provide a variety of
ways to produce the many levels of access required by these categories
Private
 The private access modifier is accessible only within the class.
29
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
int printPrivate(int x)
{
data=x;
msg();
return data;
}
}
public class Private{
public static void main(String args[]){
A obj=new A();
//System.out.println(obj.data);//Compile Time Error
System.out.println(obj.printPrivate(5));//Compile Time Error
}
}
Role of Private Constructor
 If you make any class constructor private, you cannot create the
instance of that class from outside the class :
30
class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}
Default
 If you don't use any modifier, it is treated as default by default. The default modifier is
accessible only within package. It cannot be accessed from outside the package. It
provides more accessibility than private. But, it is more restrictive than protected, and
public
31
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
Protected
 The protected access modifier is accessible within package and outside the package but through
inheritance only.
 The protected access modifier can be applied on the data member, method and constructor. It can't be
applied on the class. It provides more accessibility than the default modifer.
32
//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg(); // accessible only if B extends A otherwise not
}
}
Public
 The public access modifier is accessible everywhere. It has the widest scope
among all other modifiers.
33
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Java Access Modifiers with Method Overriding
 If you are overriding any method, overridden method (i.e. declared in subclass)
must not be more restrictive.
34
class A{
protected void msg(){System.out.println("Hello java");}
}
public class Simple extends A{
void msg(){System.out.println("Hello java");}//C.T.Error
public static void main(String args[]){
Simple obj=new Simple();
obj.msg();
}
}
35
class A {
protected void method()
{
System.out.println("Hello");
}
}
public class B extends A {
// Compile Time Error
void method()
{
System.out.println("Hello");
}
public static void main(String args[])
{
B b = new B();
b.method();
}
}
class A {
protected void method()
{
System.out.println("Hello");
}
}
public class B extends A {
public void method() // works fine
{
System.out.println("Hello");
}
public static void main(String args[])
{
B b = new B();
b.method();
}
}
Exception Handling
 The Exception Handling in Java is one of the powerful mechanism to handle
the runtime errors so that normal flow of the application can be maintained.
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.
 Java organized different exceptions condition in different classes and whenever
an exception condition occurs java runtime environment throw the object of the
related exception class.
What is Exception Handling?
 Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.
36
Hierarchy of Java Exception classes
37
Advantage of Exception Handling
 It maintain the normal flow of the application and guard the program from abnormal termination in
case an exception occurs in the program.
 An exception normally disrupts the normal flow of the application that is why we use exception handling.
 Example..
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
Suppose there are 10 statements in your program and there occurs an exception at statement 5, the rest of the
code will not be executed i.e. statement 6 to 10 will not be executed. If we perform exception handling, the rest
of the statement will be executed.
38
Exception handling mechanism
 Java exception handling is managed via five keywords: try, catch, throw, throws, and
finally.
39
Keyword Description
try The "try" keyword is used to specify a block where we should place exception
code. The try block must be followed by either catch or finally. It means, we
can't use try block alone.
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 important 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 doesn't throw an
exception. It specifies that there may occur an exception in the method. It is
always used with method signature.
Syntax for exception handling block
This is the general form of an exception-handling block:
try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb){
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...
finally {
// block of code to be executed before try block ends
}
40
Example code (Uncaught Exception)
class Exc0 {
public static void main(String args[]) {
int d = 0;
int a = 42 / d;
}
}
41
Output
run-time interpreter:
java.lang.ArithmeticException: / by zero
at Exc0.main(Exc0.java:4)
When the Java run-time system detects the attempt to divide by zero, it constructs a new
exception object and then throws this exception. This causes the execution of Exc0 to stop,
because once an exception has been thrown, it must be caught by an exception handler and
dealt with immediately.
In this example, we haven't supplied any exception handlers of our own, so the exception is
caught by the default handler provided by the Java run-time system.
Notice how the class name, Exc0; the method name, main; the filename, Exc0.java; and the
line number, 4, are all included in the simple stack trace.
Also, notice that the type of the exception thrown is a subclass of Exception called
ArithmeticException, which more specifically describes what type of error happened.
42
class Exc1 {
static void subroutine() {
int d = 0;
int a = 10 / d;
}
public static void main(String args[]) {
Exc1.subroutine();
}
}
Output:
java.lang.ArithmeticException: / by zero
at Exc1.subroutine(Exc1.java:4)
at Exc1.main(Exc1.java:7)
Example Using try and catch
43
class Exc2 {
public static void main(String args[]) {
int d, a;
try { // monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
} catch(ArithmeticException e){//catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
output:
Division by zero.
After catch statement.
Displaying a Description of an Exception
catch (ArithmeticException e) {
System.out.println("Exception: " + e);
a = 0; // set a to zero and continue }
Output:
Exception: java.lang.ArithmeticException: / by zero
44
Common Scenarios of Java Exceptions
1) A scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException.
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.
String s=null;
System.out.println(s.length());//NullPointerException
3) A scenario where NumberFormatException occurs
The wrong formatting of any value may occur NumberFormatException.
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
4) A scenario where ArrayIndexOutOfBoundsException occurs
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException 45
 We can handle the exception using the parent class exception.
46
public class TryCatchExample4 {
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
}
// handling the exception by using Exception class
catch(Exception e)
{
System.out.println(e); // print the exception
System.out.println(“Write exception handling mechanism");
}
System.out.println("rest of the code");
}
}
Exception in catch block
 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.
47
public class TryCatchExample7 {
public static void main(String[] args) {
try
{
int data1=50/0; //may throw exception
}
// handling the exception
catch(Exception e)
{
// generating the exception in catch block
int data2=50/0; //may throw exception
}
System.out.println("rest of the code");
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
Exception handling with different class
 We can not handle the generated exception (Arithmetic Exception) with a different type of exception class
(ArrayIndexOutOfBoundsException).
48
public class TryCatchExample8 {
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
}
// try to handle the ArithmeticException using ArrayIndexOutOfBoundsException
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}
}
Output:
Exception in thread "main"
java.lang.ArithmeticException: / by zero
Working of java try catch block
49
•Prints out exception description.
•Prints the stack trace (Hierarchy of methods where the exception occurred).
•Causes the program to terminate
 Unchecked Exceptions:
 They are the exceptions that are not checked at compiled time.
 In C++, all exceptions are unchecked, so it is not forced by the compiler to either handle or specify the exception.
In Java exceptions under Error and RuntimeException classes are unchecked exceptions, everything else under throwable
is checked.
50
Checked vs Unchecked Exceptions in Java
class Main {
public static void main(String args[]) {
int x = 0;
int y = 10;
int z = y/x;
}
}
Checked vs Unchecked Exceptions in Java
 Checked Exceptions:
 They are the exceptions that are checked at compile time. If some code within a method throws a checked
exception, then the method must either handle the exception or it must specify the exception using throws keyword.
51
import java.io.*;
class Main {
public static void main(String[] args) {
FileReader file = new FileReader("C:testa.txt");
BufferedReader fileInput = new BufferedReader(file);
// Print first 3 lines of file "C:testa.txt"
for (int counter = 0; counter < 3; counter++)
System.out.println(fileInput.readLine());
fileInput.close();
}
}
Output: (compile time error)
Exception in thread "main" java.lang.RuntimeException:
Uncompilable source code - unreported exception
java.io.FileNotFoundException; must be caught or declared to be
thrown at Main.main(Main.java:5)
To fix the compile time error, we either need to specify list of exceptions using throws,
or we need to use try-catch block. We have used throws in the below program.
Since FileNotFoundException is a subclass of IOException, we can just
specify IOException in the throws list and make the above program compiler-error-
free.
52
Checked vs Unchecked Exceptions in Java
Multiple catch Clauses
53
// Demonstrate multiple catch statements.
class MultiCatch {
public static void main(String args[]) {
try {
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
}
catch(ArithmeticException e) {
System.out.println("Divide by 0:"+ e);}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Arrayindexoob:"+e);}
System.out.println("After try/catch blocks.");
}
}
When you use multiple catch statements, it is important to remember that exception
subclasses must come before any of their super classes. This is because a catch
statement that uses a superclass will catch exceptions of that type plus any of its
subclasses.
54
class SuperSubCatch {
public static void main(String args[]) {
try {
int a = 0;
int b = 42 / a;
}
catch(Exception e) {
System.out.println("Generic Exception catch.");
}
/* This catch is never reached because
ArithmeticException is a subclass of Exception. */
catch(ArithmeticException e) { // ERROR - unreachable
System.out.println("This is never reached.");
}
}
}
/* This program contains an error.
A subclass must come before its superclass in a series of catch statements. If not,
unreachable code will be created and a compile-time error will result.
*/
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.
 If an inner try statement does not
have a catch handler for a particular
exception, the next try statement's
catch handlers are inspected for a
match.
 This continues until one of the catch
statements succeeds, or until all of
the nested try statements are
exhausted. If no catch statement
matches, then the Java run-time
system will handle the exception.
55
class NestTry {
public static void main(String args[]) {
try {
int a = args.length;
int b = 42 / a;
System.out.println("a = " + a);
try { // nested try block
if(a==1) a = a/(a-a); // division by zero
if(a==2) {
int c[] = { 1 };
c[42] = 99; }
} catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index out-of-bounds: " + e);
}
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
}
}
throw keyword
 The Java throw keyword is used to explicitly throw an exception.
 So far, you have only been catching exceptions that are thrown by the Java run-time
system.
 However, it is possible for your program to throw an exception explicitly, using the throw
statement given below.
throw ThrowableInstance;
 Here, ThrowableInstance must be an object of type Throwable or a subclass of
Throwable.
 The flow of execution stops immediately after the throw statement; any subsequent
statements are not executed.
 The nearest enclosing try block is inspected to see if it has a catch statement that matches
the type of the exception.
56
Example 1
public class TestThrow1{
static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}
}
57
Output:
Exception in thread main java.lang.ArithmeticException:not valid
Example 2
58
class ThrowDemo {
static void demoproc() {
try {
throw new NullPointerException("demo");
}
catch(NullPointerException e) {
System.out.println("Caught inside demoproc.");
throw e; // rethrow the exception
}
}
public static void main(String args[]) {
try {
demoproc();
} catch(NullPointerException e) {
System.out.println("Recaught: " + e);
}
}
}
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 normal flow can be
maintained.
 If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the
method can guard themselves against that exception.
 This is the general form of a method declaration that includes a throws clause:
type method-name(parameter-list) throws exception-list
{
// body of method
}
 Here, exception-list is a comma-separated list of the exceptions that a method can throw.
 This is necessary for all exceptions, except those of type Error or RuntimeException, or any of their subclasses.
 All other exceptions that a method can throw must be declared in the throws clause. If they are not, a compile-time error
will result.
59
Example 1
// This program contains an error and will not compile.
class ThrowsDemo {
static void throwOne() {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
throwOne();
}
}
60
Example 2 (Correct version of Ex1)
// This is now correct.
class ThrowsDemo {
static void throwOne() throws IllegalAccessException
{
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
} catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}
}
}
61
One more example
62
import java.io.IOException;
class Testthrows1
{
void m()throws IOException{
throw new IOException("device error");//checked exception
}
void n()throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}
Difference between throw and throws in Java
63
No. throw throws
1) Java throw keyword is used to explicitly
throw an exception.
Java throws keyword is used to declare an
exception.
2) Checked exception cannot be
propagated using throw only.
Checked exception can be propagated with
throws.
3) Throw is followed by an instance. Throws is followed by class.
4) Throw is used within the method. Throws is used with the method signature.
5) You cannot throw multiple exceptions. You can declare multiple exceptions e.g.
public void method()throws
IOException,SQLException.
Java finally block
 Java finally block is a block that is used to execute important code such as closing
connection, stream etc.
 Java finally block is always executed whether exception is handled or not.
 Java finally block follows try or catch block.
64
 If an exception is thrown, the
finally block will execute even if
no catch statement matches the
exception.
 Any time a method is about to
return to the caller from inside a
try/catch block, via an uncaught
exception or an explicit return
statement, the finally clause is also
executed just before the method
returns.
Example 1
class TestFinallyBlock1{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e){
System.out.println(e);
}
finally{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
} 65
66
class FinallyDemo {
static void procA() {
try {
System.out.println("inside procA");
throw new RuntimeException("demo");}
finally {
System.out.println("procA's finally");
}
}
static void procB() {
try {
System.out.println("inside procB");
return;
}
finally {
System.out.println("procB's finally");}
}
static void procC() {
try {
System.out.println("inside procC");
}
finally {
System.out.println("procC's finally");
}
}
public static void main(String args[]) {
try {
procA();
}
catch (Exception e) {
System.out.println("Exception caught");
}
procB();
procC();
}
}
Output
inside procA
procA's finally
Exception caught
inside procB
procB's finally
inside procC
procC's finally
Java Exception propagation
 In a method calling, an exception is first thrown from the top of the stack and if it is not
caught, it drops down the call stack to the previous method, If not caught there, the
exception again drops down to the previous method, and so on until they are caught or
until they reach the very bottom of the call stack. This is called exception propagation.
67
class TestExceptionPropagation1{
void m(){
int data=50/0;
}
void n(){
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
TestExceptionPropagation1 obj=new TestExceptionPropagation1();
obj.p();
System.out.println("normal flow...");
}
}
By default Unchecked Exceptions are
forwarded in calling chain (propagated).
Checked exception propagation
68
class TestExceptionPropagation2{
void m(){
throw new java.io.IOException("device error");//checked exception
}
void n(){
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handeled");}
}
public static void main(String args[]){
TestExceptionPropagation2 obj=new TestExceptionPropagation2();
obj.p();
System.out.println("normal flow");
}
}
By default, Checked Exceptions are not
forwarded in calling chain (propagated).
Output: Compile Time Error
Java User Defined Exceptions
 If you are creating your own Exception that is known as custom exception or user-defined exception.
 You can define your exception class by extending Exception class or its any subclass.
69
class InvalidAgeException extends Exception{
InvalidAgeException(String s)
{
super(s);
}
}
70
class InvalidAgeException extends Exception{
InvalidAgeException(String s){
super(s);
}
}
class TestCustomException1{
static void validate(int age)throws InvalidAgeException{
if(age<18)
throw new InvalidAgeException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
try{
validate(13);
}
catch(Exception m){System.out.println("Exception occured: "+m);}
System.out.println("rest of the code...");
}
}
Output:
Exception occured: InvalidAgeException:not valid
rest of the code...
Exception Handling with Method Overriding
 There are some rules if we talk about method overriding with exception handling.
 If the superclass method does not declare an exception
• If the superclass method does not declare an exception, subclass overridden method cannot declare the
checked exception but it can declare unchecked exception.
 If the superclass method declares an exception
• If the superclass method declares an exception, subclass overridden method can declare same, subclass
exception or no exception but cannot declare parent exception.
71
If the superclass method does not declare an exception
72
/*If the superclass method does not declare an
exception, subclass overridden method cannot
declare the checked exception.*/
import java.io.*;
class Parent{
void msg(){System.out.println("parent");}
}
class TestExceptionChild extends Parent{
void msg()throws IOException{
System.out.println("TestExceptionChild");
}
public static void main(String args[]){
Parent p=new TestExceptionChild();
p.msg();
}
}
// compile time error
/*If the superclass method does not declare an
exception, subclass overridden method cannot
declare the checked exception but can declare
unchecked exception.*/
import java.io.*;
class Parent{
void msg(){System.out.println("parent");}
}
class TestExceptionChild1 extends Parent{
void msg()throws ArithmeticException{
System.out.println("child");
}
public static void main(String args[]){
Parent p=new TestExceptionChild1();
p.msg();
}
}
Output: child
If the superclass method declares an exception
73
If the superclass method declares an exception,
subclass overridden method can declare same,
subclass exception or no exception but cannot
declare parent exception.
import java.io.*;
class Parent{
void msg()throws ArithmeticException{
System.out.println("parent");}
}
class TestExceptionChild2 extends Parent{
void msg()throws Exception
{
System.out.println("child");}
public static void main(String args[]){
Parent p=new TestExceptionChild2();
try{
p.msg();
}catch(Exception e){}
}
}
Output: compile time error
/* Correct Code: case subclass overridden method
declares same exception
*/
import java.io.*;
class Parent{
void msg()throws Exception{
System.out.println("parent");}
}
class TestExceptionChild3 extends Parent{
void msg()throws Exception{
System.out.println("child");}
public static void main(String args[]){
Parent p=new TestExceptionChild3();
try{
p.msg();
}catch(Exception e){}
}
}
Output: child
74
/*Case: subclass overridden method declares
subclass exception*/
import java.io.*;
class Parent{
void msg()throws Exception
{System.out.println("parent");}
}
class TestExceptionChild4 extends Parent{
void msg()throws ArithmeticException
{System.out.println("child");}
public static void main(String args[]){
Parent p=new TestExceptionChild4();
try{
p.msg();
}catch(Exception e){}
}
}
Output: child
/*Case: subclass overridden method declares no
exception*/
import java.io.*;
class Parent{
void msg()throws Exception
{System.out.println("parent");}
}
class TestExceptionChild5 extends Parent
{
void msg()
{System.out.println("child");}
public static void main(String args[]){
Parent p=new TestExceptionChild5();
try{
p.msg();
}catch(Exception e){}
}
}
Output: child

More Related Content

PPTX
abstract,final,interface (1).pptx upload
PPT
oops with java modules i & ii.ppt
PPTX
Interface in java
PPTX
OOP with Java - Abstract Classes and Interfaces
PDF
21UCAC31 Java Programming.pdf(MTNC)(BCA)
PPTX
it is the quick gest about the interfaces in java
PPTX
INTERFACES. with machine learning and data
PDF
Basic_Java_10.pdf
abstract,final,interface (1).pptx upload
oops with java modules i & ii.ppt
Interface in java
OOP with Java - Abstract Classes and Interfaces
21UCAC31 Java Programming.pdf(MTNC)(BCA)
it is the quick gest about the interfaces in java
INTERFACES. with machine learning and data
Basic_Java_10.pdf

Similar to Exception handling and packages.pdf (20)

PPT
ABSTRACT CLASSES AND INTERFACES.ppt
PPTX
Interface in java
PDF
Core Java Interface Concepts for BCA Studetns
DOCX
Core java notes with examples
PPTX
Inheritance & interface ppt Inheritance
PPTX
Lecture 8 abstract class and interface
PPTX
Objects and classes in OO Programming concepts
PDF
java-06inheritance
DOCX
Java interface
PPS
Interface
PPT
Lec8_Java Advanced class features_Part 1V.ppt
PPTX
Interface in java ,multiple inheritance in java, interface implementation
DOCX
Binding,interface,abstarct class
PPT
Java interface
PPTX
Interface
PPTX
Session 10 - OOP with Java - Abstract Classes and Interfaces
PDF
polymorphismpresentation-160825122725.pdf
PPSX
OOP with Java - Abstract Classes and Interfaces
PPTX
Polymorphism presentation in java
PPTX
Java notes of Chapter 3 presentation slides
ABSTRACT CLASSES AND INTERFACES.ppt
Interface in java
Core Java Interface Concepts for BCA Studetns
Core java notes with examples
Inheritance & interface ppt Inheritance
Lecture 8 abstract class and interface
Objects and classes in OO Programming concepts
java-06inheritance
Java interface
Interface
Lec8_Java Advanced class features_Part 1V.ppt
Interface in java ,multiple inheritance in java, interface implementation
Binding,interface,abstarct class
Java interface
Interface
Session 10 - OOP with Java - Abstract Classes and Interfaces
polymorphismpresentation-160825122725.pdf
OOP with Java - Abstract Classes and Interfaces
Polymorphism presentation in java
Java notes of Chapter 3 presentation slides
Ad

Recently uploaded (20)

PDF
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
PDF
PPT on Performance Review to get promotions
PDF
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PPTX
Internet of Things (IOT) - A guide to understanding
PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
PPTX
Construction Project Organization Group 2.pptx
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PPTX
Sustainable Sites - Green Building Construction
PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PPT
Project quality management in manufacturing
PDF
Categorization of Factors Affecting Classification Algorithms Selection
PPTX
UNIT-1 - COAL BASED THERMAL POWER PLANTS
PPTX
Fundamentals of Mechanical Engineering.pptx
PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
PDF
Artificial Superintelligence (ASI) Alliance Vision Paper.pdf
PDF
PREDICTION OF DIABETES FROM ELECTRONIC HEALTH RECORDS
PPT
Introduction, IoT Design Methodology, Case Study on IoT System for Weather Mo...
PPT
Mechanical Engineering MATERIALS Selection
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
PPT on Performance Review to get promotions
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
Internet of Things (IOT) - A guide to understanding
CYBER-CRIMES AND SECURITY A guide to understanding
Construction Project Organization Group 2.pptx
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
Foundation to blockchain - A guide to Blockchain Tech
Sustainable Sites - Green Building Construction
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
Project quality management in manufacturing
Categorization of Factors Affecting Classification Algorithms Selection
UNIT-1 - COAL BASED THERMAL POWER PLANTS
Fundamentals of Mechanical Engineering.pptx
Automation-in-Manufacturing-Chapter-Introduction.pdf
Artificial Superintelligence (ASI) Alliance Vision Paper.pdf
PREDICTION OF DIABETES FROM ELECTRONIC HEALTH RECORDS
Introduction, IoT Design Methodology, Case Study on IoT System for Weather Mo...
Mechanical Engineering MATERIALS Selection
Ad

Exception handling and packages.pdf

  • 2. Using Abstract Classes  There are situations in which you will want to define a superclass that declares the structure of a given abstraction without providing a complete implementation of every method.  That is, sometimes you will want to create a superclass that only defines a generalized form that will be shared by all of its subclasses, leaving it to each subclass to fill in the details.  Such a class determines the nature of the methods that the subclasses must implement.  One way this situation can occur is when a superclass is unable to create a meaningful implementation for a method. 2
  • 3. Abstraction in Java  Abstraction is a process of hiding the implementation details and showing only functionality to the user.  Abstraction lets you focus on what the object does instead of how it does it.  There are two ways to achieve abstraction in java • Abstract class (0 to 100%) • Interface (100%) 3
  • 4. Abstract class in Java  A class which is declared with the abstract keyword is known as an abstract class.  It can have abstract and non-abstract methods (method with the body).  A class which extends an abstract class must implement all the abstract methods in abstract class otherwise the class should be defined as an abstract class.  It cannot be instantiated. Some important points • An abstract class must be declared with an abstract keyword. • It can have abstract and non-abstract methods. • It can have constructors and static methods also. • It can have final methods which will force the subclass not to change the body of the method. 4
  • 5. Example of Abstract class that has an abstract method abstract class Bike{ abstract void run(); } class Honda4 extends Bike{ void run() { System.out.println("running safely"); } public static void main(String args[]){ Bike obj = new Honda4(); obj.run(); } } 5
  • 6. One more example of overriding 6 // Using run-time polymorphism. abstract class Figure { double dim1; double dim2; Figure(double a, double b) { dim1 = a; dim2 = b; } abstract double area(); } class Rectangle extends Figure { Rectangle(double a, double b) { super(a, b); } // override area for rectangle double area() { // must be override all abstract methods of abstract class System.out.println("Inside Area for Rectangle."); return dim1 * dim2; } }
  • 7. 7 class Triangle extends Figure { Triangle(double a, double b) { super(a, b);} double area() { System.out.println("Inside Area for Triangle."); return dim1 * dim2 / 2;} } class FindAreas { public static void main(String args[]) { //Figure f = new Figure(10, 10); Rectangle r = new Rectangle(9, 5); Triangle t = new Triangle(10, 8); Figure figref; figref = r; System.out.println("Area is " + figref.area()); figref = t; System.out.println("Area is " + figref.area()); figref = f; System.out.println("Area is " + figref.area()); } }
  • 8. Understanding the real scenario of Abstract class  In previous example, Figure is the abstract class, and its implementation is provided by the Rectangle and Triangle 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. We will learn about the factory method later.  In this example, if you create the instance of Rectangle class, draw() method of Rectangle class will be invoked. 8
  • 9. One more example abstract class Figure{ abstract void draw(); } //In real scenario, implementation is provided by others i.e. unknown by end user class Rectangle extends Figure{ void draw(){System.out.println("drawing rectangle");} } class Triangle extends Figure{ void draw(){System.out.println("drawing Triangle");} } //In real scenario, method is called by programmer or user class TestAbstraction1{ public static void main(String args[]){ Figure f=new Triangle(); //In a real scenario, object is provided through method, e.g., getShape() method f.draw(); } } 9
  • 10. Interface in Java  An interface in Java is a blueprint of a class.  All variable in interfaces are implicitly static final and all methods are abstract methods.  The interface in Java is a mechanism to achieve abstraction. It is used to achieve abstraction and multiple inheritance in Java.  It cannot be instantiated just like the abstract class. 10
  • 11. 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.  A class implements interface while and interface extends other interfaces.  The Java compiler adds public and abstract keywords before the interface method. Moreover, it adds public, static and final keywords before data members. 11
  • 12. The relationship between classes and interfaces 12
  • 13. How to define interface  An interface is defined much like a class. This is the general form of an interface: access interface name { return-type method-name1(parameter-list); return-type method-name2(parameter-list); type final-varname1 = value; type final-varname2 = value; // ... return-type method-nameN(parameter-list); 13 Here, access is either public or not used. When no access specifier is included, then default access results, and the interface is only available to other members of the package in which it is declared. When it is declared as public, the interface can be used by any other code.
  • 14. Java Interface Example 14 interface printable { void print(); } class A6 implements printable { public void print() {System.out.println("Hello"); } public static void main(String args[]){ A6 obj = new A6(); obj.print(); } }
  • 15. Java Interface Example: Drawable 15 //Interface declaration: by first user interface Drawable{ void draw(); } //Implementation: by second user class Rectangle implements Drawable{ public void draw(){System.out.println("drawing rectangle");} } class Circle implements Drawable{ public void draw(){System.out.println("drawing circle");} } //Using interface: by third user class TestInterface1{ public static void main(String args[]){ Drawable d=new Circle(); //In real scenario, object is provided by method e.g. getDrawable() d.draw(); } } 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.
  • 16. Interfaces Can Be Extended 16 // One interface can extend another. interface A { void meth1(); void meth2(); } // B now includes meth1() and meth2() — it adds meth3(). interface B extends A { void meth3(); } // This class must implement all of A and B class MyClass implements B { public void meth1() { System.out.println("Implement meth1()."); } public void meth2() { System.out.println("Implement meth2()."); } public void meth3() { System.out.println("Implement meth3()."); } } class IFExtend { public static void main(String arg[]) { MyClass ob = new MyClass(); ob.meth1(); ob.meth2(); ob.meth3(); }
  • 17. Multiple inheritance in Java by interface  If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known as multiple inheritance. 17
  • 18. 18 interface Printable{ void print(); } interface Showable{ void show(); } class A7 implements Printable,Showable { public void print(){ System.out.println("Hello");} public void show(){ System.out.println("Welcome");} public static void main(String args[]){ A7 obj = new A7(); obj.print(); obj.show(); } }
  • 19. Difference between abstract class and interface 19 Abstract class Interface 1) Abstract class can have abstract and non- abstract methods. Interface can have only abstract methods. Since Java 8, it can have default and static methods also. 2) Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance. 3) Abstract class can have final, non-final, static and non-static variables. Interface has only static and final variables. 4) Abstract class can provide the implementation of interface. Interface can't provide the implementation of abstract class. 5) The abstract keyword is used to declare abstract class. The interface keyword is used to declare interface. 6) An abstract class can extend another Java class and implement multiple Java interfaces. An interface can extend another Java interface only. 7) An abstract class can be extended using keyword "extends". An interface can be implemented using keyword "implements". 8) A Java abstract class can have class members like private, protected, etc. Members of a Java interface are public by default. 9)Example: public abstract class Shape{ public abstract void draw(); } Example: public interface Drawable{ void draw(); }
  • 20. Java Packages  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. 20
  • 22. Defining a Package  This is the general form of the package statement: package pkg;  For example, the following statement creates a package called MyPackage containing a class A package MyPackage; class A{ void show() { System.out.println(“print A”); } }  Java uses file system directories to store packages.  For example, the .class files for any classes you declare to be part of MyPackage must be stored in a directory called MyPackage. 22
  • 23.  More than one file can include the same package statement. The package statement simply specifies to which package the classes defined in a file belong.  Most real-world packages are spread across many files.  You can create a hierarchy of packages. To do so, simply separate each package name from the one above it by use of a period. Syntax package pkg1[.pkg2[.pkg3]]; Example package java.awt.image; 23
  • 24. A Short Package Example package MyPack; class Balance { String name; double bal; Balance(String n, double b) { name = n; bal = b;} void show() { if(bal<0) System.out.print("—> "); System.out.println(name + ": $" + bal);} } class AccountBalance { public static void main(String args[]) { Balance current[] = new Balance[3]; current[0] = new Balance("K. J. Fielding", 123.23); current[1] = new Balance("Will Tell", 157.02); current[2] = new Balance("Tom Jackson", -12.33); for(int i=0; i<3; i++) current[i].show();} } 24
  • 25. Package compilation  Create a directory with the name MyPack in current directory  Save the file with “AccountBalance.java” in MyPack  Write following command in current working directory where you have created MyPack to compile the package javac MyPackAccountBalance.java  The above command will create a package MyPack containg two .class files Balance.java and AccountBalance. Java  If you don’t want to create MyPack directory then using following command the directory will be created by command itself within the current directory..  Save your java file in current directory and execute following command to create the package MyPack javac –d . AccountBalance.java 25
  • 26. Running the class inside a package  Execute the AccountBalance class, using the following command java MyPack.AccountBalance  Remember, you will need to be in the directory above MyPack when you execute this command, or to have your CLASSPATH environmental variable set appropriately. 26
  • 27. Packages and Member Access  Classes and packages are both means of encapsulating and containing the name space and scope of variables and methods.  Packages act as containers for classes and other subordinate packages.  Classes act as containers for data and code. The class is Java's smallest unit of abstraction.  Java addresses four categories of visibility for class members: 1. Subclasses in the same package 2. Non-subclasses in the same package 3. Subclasses in different packages 4. Classes that are neither in the same package nor subclasses 27
  • 28. Access Control 28 The three access specifiers, private, public, and protected, provide a variety of ways to produce the many levels of access required by these categories
  • 29. Private  The private access modifier is accessible only within the class. 29 class A{ private int data=40; private void msg(){System.out.println("Hello java");} } public class Simple{ public static void main(String args[]){ A obj=new A(); System.out.println(obj.data);//Compile Time Error obj.msg();//Compile Time Error } } class A{ private int data=40; private void msg(){System.out.println("Hello java");} int printPrivate(int x) { data=x; msg(); return data; } } public class Private{ public static void main(String args[]){ A obj=new A(); //System.out.println(obj.data);//Compile Time Error System.out.println(obj.printPrivate(5));//Compile Time Error } }
  • 30. Role of Private Constructor  If you make any class constructor private, you cannot create the instance of that class from outside the class : 30 class A{ private A(){}//private constructor void msg(){System.out.println("Hello java");} } public class Simple{ public static void main(String args[]){ A obj=new A();//Compile Time Error } }
  • 31. Default  If you don't use any modifier, it is treated as default by default. The default modifier is accessible only within package. It cannot be accessed from outside the package. It provides more accessibility than private. But, it is more restrictive than protected, and public 31 //save by A.java package pack; class A{ void msg(){System.out.println("Hello");} } //save by B.java package mypack; import pack.*; class B{ public static void main(String args[]){ A obj = new A();//Compile Time Error obj.msg();//Compile Time Error } }
  • 32. Protected  The protected access modifier is accessible within package and outside the package but through inheritance only.  The protected access modifier can be applied on the data member, method and constructor. It can't be applied on the class. It provides more accessibility than the default modifer. 32 //save by A.java package pack; public class A{ protected void msg(){System.out.println("Hello");} } //save by B.java package mypack; import pack.*; class B extends A{ public static void main(String args[]){ B obj = new B(); obj.msg(); // accessible only if B extends A otherwise not } }
  • 33. Public  The public access modifier is accessible everywhere. It has the widest scope among all other modifiers. 33 //save by A.java package pack; public class A{ public void msg(){System.out.println("Hello");} } //save by B.java package mypack; import pack.*; class B{ public static void main(String args[]){ A obj = new A(); obj.msg(); } }
  • 34. Java Access Modifiers with Method Overriding  If you are overriding any method, overridden method (i.e. declared in subclass) must not be more restrictive. 34 class A{ protected void msg(){System.out.println("Hello java");} } public class Simple extends A{ void msg(){System.out.println("Hello java");}//C.T.Error public static void main(String args[]){ Simple obj=new Simple(); obj.msg(); } }
  • 35. 35 class A { protected void method() { System.out.println("Hello"); } } public class B extends A { // Compile Time Error void method() { System.out.println("Hello"); } public static void main(String args[]) { B b = new B(); b.method(); } } class A { protected void method() { System.out.println("Hello"); } } public class B extends A { public void method() // works fine { System.out.println("Hello"); } public static void main(String args[]) { B b = new B(); b.method(); } }
  • 36. Exception Handling  The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so that normal flow of the application can be maintained. 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.  Java organized different exceptions condition in different classes and whenever an exception condition occurs java runtime environment throw the object of the related exception class. What is Exception Handling?  Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc. 36
  • 37. Hierarchy of Java Exception classes 37
  • 38. Advantage of Exception Handling  It maintain the normal flow of the application and guard the program from abnormal termination in case an exception occurs in the program.  An exception normally disrupts the normal flow of the application that is why we use exception handling.  Example.. statement 1; statement 2; statement 3; statement 4; statement 5;//exception occurs statement 6; statement 7; statement 8; statement 9; statement 10; Suppose there are 10 statements in your program and there occurs an exception at statement 5, the rest of the code will not be executed i.e. statement 6 to 10 will not be executed. If we perform exception handling, the rest of the statement will be executed. 38
  • 39. Exception handling mechanism  Java exception handling is managed via five keywords: try, catch, throw, throws, and finally. 39 Keyword Description try The "try" keyword is used to specify a block where we should place exception code. The try block must be followed by either catch or finally. It means, we can't use try block alone. 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 important 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 doesn't throw an exception. It specifies that there may occur an exception in the method. It is always used with method signature.
  • 40. Syntax for exception handling block This is the general form of an exception-handling block: try { // block of code to monitor for errors } catch (ExceptionType1 exOb){ // exception handler for ExceptionType1 } catch (ExceptionType2 exOb) { // exception handler for ExceptionType2 } // ... finally { // block of code to be executed before try block ends } 40
  • 41. Example code (Uncaught Exception) class Exc0 { public static void main(String args[]) { int d = 0; int a = 42 / d; } } 41 Output run-time interpreter: java.lang.ArithmeticException: / by zero at Exc0.main(Exc0.java:4) When the Java run-time system detects the attempt to divide by zero, it constructs a new exception object and then throws this exception. This causes the execution of Exc0 to stop, because once an exception has been thrown, it must be caught by an exception handler and dealt with immediately. In this example, we haven't supplied any exception handlers of our own, so the exception is caught by the default handler provided by the Java run-time system. Notice how the class name, Exc0; the method name, main; the filename, Exc0.java; and the line number, 4, are all included in the simple stack trace. Also, notice that the type of the exception thrown is a subclass of Exception called ArithmeticException, which more specifically describes what type of error happened.
  • 42. 42 class Exc1 { static void subroutine() { int d = 0; int a = 10 / d; } public static void main(String args[]) { Exc1.subroutine(); } } Output: java.lang.ArithmeticException: / by zero at Exc1.subroutine(Exc1.java:4) at Exc1.main(Exc1.java:7)
  • 43. Example Using try and catch 43 class Exc2 { public static void main(String args[]) { int d, a; try { // monitor a block of code. d = 0; a = 42 / d; System.out.println("This will not be printed."); } catch(ArithmeticException e){//catch divide-by-zero error System.out.println("Division by zero."); } System.out.println("After catch statement."); } } output: Division by zero. After catch statement.
  • 44. Displaying a Description of an Exception catch (ArithmeticException e) { System.out.println("Exception: " + e); a = 0; // set a to zero and continue } Output: Exception: java.lang.ArithmeticException: / by zero 44
  • 45. Common Scenarios of Java Exceptions 1) A scenario where ArithmeticException occurs If we divide any number by zero, there occurs an ArithmeticException. 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. String s=null; System.out.println(s.length());//NullPointerException 3) A scenario where NumberFormatException occurs The wrong formatting of any value may occur NumberFormatException. String s="abc"; int i=Integer.parseInt(s);//NumberFormatException 4) A scenario where ArrayIndexOutOfBoundsException occurs int a[]=new int[5]; a[10]=50; //ArrayIndexOutOfBoundsException 45
  • 46.  We can handle the exception using the parent class exception. 46 public class TryCatchExample4 { public static void main(String[] args) { try { int data=50/0; //may throw exception } // handling the exception by using Exception class catch(Exception e) { System.out.println(e); // print the exception System.out.println(“Write exception handling mechanism"); } System.out.println("rest of the code"); } }
  • 47. Exception in catch block  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. 47 public class TryCatchExample7 { public static void main(String[] args) { try { int data1=50/0; //may throw exception } // handling the exception catch(Exception e) { // generating the exception in catch block int data2=50/0; //may throw exception } System.out.println("rest of the code"); } } Output: Exception in thread "main" java.lang.ArithmeticException: / by zero
  • 48. Exception handling with different class  We can not handle the generated exception (Arithmetic Exception) with a different type of exception class (ArrayIndexOutOfBoundsException). 48 public class TryCatchExample8 { public static void main(String[] args) { try { int data=50/0; //may throw exception } // try to handle the ArithmeticException using ArrayIndexOutOfBoundsException catch(ArrayIndexOutOfBoundsException e) { System.out.println(e); } System.out.println("rest of the code"); } } Output: Exception in thread "main" java.lang.ArithmeticException: / by zero
  • 49. Working of java try catch block 49 •Prints out exception description. •Prints the stack trace (Hierarchy of methods where the exception occurred). •Causes the program to terminate
  • 50.  Unchecked Exceptions:  They are the exceptions that are not checked at compiled time.  In C++, all exceptions are unchecked, so it is not forced by the compiler to either handle or specify the exception. In Java exceptions under Error and RuntimeException classes are unchecked exceptions, everything else under throwable is checked. 50 Checked vs Unchecked Exceptions in Java class Main { public static void main(String args[]) { int x = 0; int y = 10; int z = y/x; } }
  • 51. Checked vs Unchecked Exceptions in Java  Checked Exceptions:  They are the exceptions that are checked at compile time. If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception using throws keyword. 51 import java.io.*; class Main { public static void main(String[] args) { FileReader file = new FileReader("C:testa.txt"); BufferedReader fileInput = new BufferedReader(file); // Print first 3 lines of file "C:testa.txt" for (int counter = 0; counter < 3; counter++) System.out.println(fileInput.readLine()); fileInput.close(); } } Output: (compile time error) Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown at Main.main(Main.java:5) To fix the compile time error, we either need to specify list of exceptions using throws, or we need to use try-catch block. We have used throws in the below program. Since FileNotFoundException is a subclass of IOException, we can just specify IOException in the throws list and make the above program compiler-error- free.
  • 52. 52 Checked vs Unchecked Exceptions in Java
  • 53. Multiple catch Clauses 53 // Demonstrate multiple catch statements. class MultiCatch { public static void main(String args[]) { try { int a = args.length; System.out.println("a = " + a); int b = 42 / a; int c[] = { 1 }; c[42] = 99; } catch(ArithmeticException e) { System.out.println("Divide by 0:"+ e);} catch(ArrayIndexOutOfBoundsException e) { System.out.println("Arrayindexoob:"+e);} System.out.println("After try/catch blocks."); } } When you use multiple catch statements, it is important to remember that exception subclasses must come before any of their super classes. This is because a catch statement that uses a superclass will catch exceptions of that type plus any of its subclasses.
  • 54. 54 class SuperSubCatch { public static void main(String args[]) { try { int a = 0; int b = 42 / a; } catch(Exception e) { System.out.println("Generic Exception catch."); } /* This catch is never reached because ArithmeticException is a subclass of Exception. */ catch(ArithmeticException e) { // ERROR - unreachable System.out.println("This is never reached."); } } } /* This program contains an error. A subclass must come before its superclass in a series of catch statements. If not, unreachable code will be created and a compile-time error will result. */
  • 55. 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.  If an inner try statement does not have a catch handler for a particular exception, the next try statement's catch handlers are inspected for a match.  This continues until one of the catch statements succeeds, or until all of the nested try statements are exhausted. If no catch statement matches, then the Java run-time system will handle the exception. 55 class NestTry { public static void main(String args[]) { try { int a = args.length; int b = 42 / a; System.out.println("a = " + a); try { // nested try block if(a==1) a = a/(a-a); // division by zero if(a==2) { int c[] = { 1 }; c[42] = 99; } } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array index out-of-bounds: " + e); } } catch(ArithmeticException e) { System.out.println("Divide by 0: " + e); } } }
  • 56. throw keyword  The Java throw keyword is used to explicitly throw an exception.  So far, you have only been catching exceptions that are thrown by the Java run-time system.  However, it is possible for your program to throw an exception explicitly, using the throw statement given below. throw ThrowableInstance;  Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable.  The flow of execution stops immediately after the throw statement; any subsequent statements are not executed.  The nearest enclosing try block is inspected to see if it has a catch statement that matches the type of the exception. 56
  • 57. Example 1 public class TestThrow1{ static void validate(int age){ if(age<18) throw new ArithmeticException("not valid"); else System.out.println("welcome to vote"); } public static void main(String args[]){ validate(13); System.out.println("rest of the code..."); } } 57 Output: Exception in thread main java.lang.ArithmeticException:not valid
  • 58. Example 2 58 class ThrowDemo { static void demoproc() { try { throw new NullPointerException("demo"); } catch(NullPointerException e) { System.out.println("Caught inside demoproc."); throw e; // rethrow the exception } } public static void main(String args[]) { try { demoproc(); } catch(NullPointerException e) { System.out.println("Recaught: " + e); } } }
  • 59. 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 normal flow can be maintained.  If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception.  This is the general form of a method declaration that includes a throws clause: type method-name(parameter-list) throws exception-list { // body of method }  Here, exception-list is a comma-separated list of the exceptions that a method can throw.  This is necessary for all exceptions, except those of type Error or RuntimeException, or any of their subclasses.  All other exceptions that a method can throw must be declared in the throws clause. If they are not, a compile-time error will result. 59
  • 60. Example 1 // This program contains an error and will not compile. class ThrowsDemo { static void throwOne() { System.out.println("Inside throwOne."); throw new IllegalAccessException("demo"); } public static void main(String args[]) { throwOne(); } } 60
  • 61. Example 2 (Correct version of Ex1) // This is now correct. class ThrowsDemo { static void throwOne() throws IllegalAccessException { System.out.println("Inside throwOne."); throw new IllegalAccessException("demo"); } public static void main(String args[]) { try { throwOne(); } catch (IllegalAccessException e) { System.out.println("Caught " + e); } } } 61
  • 62. One more example 62 import java.io.IOException; class Testthrows1 { void m()throws IOException{ throw new IOException("device error");//checked exception } void n()throws IOException{ m(); } void p(){ try{ n(); }catch(Exception e){System.out.println("exception handled");} } public static void main(String args[]){ Testthrows1 obj=new Testthrows1(); obj.p(); System.out.println("normal flow..."); } }
  • 63. Difference between throw and throws in Java 63 No. throw throws 1) Java throw keyword is used to explicitly throw an exception. Java throws keyword is used to declare an exception. 2) Checked exception cannot be propagated using throw only. Checked exception can be propagated with throws. 3) Throw is followed by an instance. Throws is followed by class. 4) Throw is used within the method. Throws is used with the method signature. 5) You cannot throw multiple exceptions. You can declare multiple exceptions e.g. public void method()throws IOException,SQLException.
  • 64. Java finally block  Java finally block is a block that is used to execute important code such as closing connection, stream etc.  Java finally block is always executed whether exception is handled or not.  Java finally block follows try or catch block. 64  If an exception is thrown, the finally block will execute even if no catch statement matches the exception.  Any time a method is about to return to the caller from inside a try/catch block, via an uncaught exception or an explicit return statement, the finally clause is also executed just before the method returns.
  • 65. Example 1 class TestFinallyBlock1{ public static void main(String args[]){ try{ int data=25/0; System.out.println(data); } catch(NullPointerException e){ System.out.println(e); } finally{ System.out.println("finally block is always executed"); } System.out.println("rest of the code..."); } } 65
  • 66. 66 class FinallyDemo { static void procA() { try { System.out.println("inside procA"); throw new RuntimeException("demo");} finally { System.out.println("procA's finally"); } } static void procB() { try { System.out.println("inside procB"); return; } finally { System.out.println("procB's finally");} } static void procC() { try { System.out.println("inside procC"); } finally { System.out.println("procC's finally"); } } public static void main(String args[]) { try { procA(); } catch (Exception e) { System.out.println("Exception caught"); } procB(); procC(); } } Output inside procA procA's finally Exception caught inside procB procB's finally inside procC procC's finally
  • 67. Java Exception propagation  In a method calling, an exception is first thrown from the top of the stack and if it is not caught, it drops down the call stack to the previous method, If not caught there, the exception again drops down to the previous method, and so on until they are caught or until they reach the very bottom of the call stack. This is called exception propagation. 67 class TestExceptionPropagation1{ void m(){ int data=50/0; } void n(){ m(); } void p(){ try{ n(); }catch(Exception e){System.out.println("exception handled");} } public static void main(String args[]){ TestExceptionPropagation1 obj=new TestExceptionPropagation1(); obj.p(); System.out.println("normal flow..."); } } By default Unchecked Exceptions are forwarded in calling chain (propagated).
  • 68. Checked exception propagation 68 class TestExceptionPropagation2{ void m(){ throw new java.io.IOException("device error");//checked exception } void n(){ m(); } void p(){ try{ n(); }catch(Exception e){System.out.println("exception handeled");} } public static void main(String args[]){ TestExceptionPropagation2 obj=new TestExceptionPropagation2(); obj.p(); System.out.println("normal flow"); } } By default, Checked Exceptions are not forwarded in calling chain (propagated). Output: Compile Time Error
  • 69. Java User Defined Exceptions  If you are creating your own Exception that is known as custom exception or user-defined exception.  You can define your exception class by extending Exception class or its any subclass. 69 class InvalidAgeException extends Exception{ InvalidAgeException(String s) { super(s); } }
  • 70. 70 class InvalidAgeException extends Exception{ InvalidAgeException(String s){ super(s); } } class TestCustomException1{ static void validate(int age)throws InvalidAgeException{ if(age<18) throw new InvalidAgeException("not valid"); else System.out.println("welcome to vote"); } public static void main(String args[]){ try{ validate(13); } catch(Exception m){System.out.println("Exception occured: "+m);} System.out.println("rest of the code..."); } } Output: Exception occured: InvalidAgeException:not valid rest of the code...
  • 71. Exception Handling with Method Overriding  There are some rules if we talk about method overriding with exception handling.  If the superclass method does not declare an exception • If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception but it can declare unchecked exception.  If the superclass method declares an exception • If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception. 71
  • 72. If the superclass method does not declare an exception 72 /*If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception.*/ import java.io.*; class Parent{ void msg(){System.out.println("parent");} } class TestExceptionChild extends Parent{ void msg()throws IOException{ System.out.println("TestExceptionChild"); } public static void main(String args[]){ Parent p=new TestExceptionChild(); p.msg(); } } // compile time error /*If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception but can declare unchecked exception.*/ import java.io.*; class Parent{ void msg(){System.out.println("parent");} } class TestExceptionChild1 extends Parent{ void msg()throws ArithmeticException{ System.out.println("child"); } public static void main(String args[]){ Parent p=new TestExceptionChild1(); p.msg(); } } Output: child
  • 73. If the superclass method declares an exception 73 If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception. import java.io.*; class Parent{ void msg()throws ArithmeticException{ System.out.println("parent");} } class TestExceptionChild2 extends Parent{ void msg()throws Exception { System.out.println("child");} public static void main(String args[]){ Parent p=new TestExceptionChild2(); try{ p.msg(); }catch(Exception e){} } } Output: compile time error /* Correct Code: case subclass overridden method declares same exception */ import java.io.*; class Parent{ void msg()throws Exception{ System.out.println("parent");} } class TestExceptionChild3 extends Parent{ void msg()throws Exception{ System.out.println("child");} public static void main(String args[]){ Parent p=new TestExceptionChild3(); try{ p.msg(); }catch(Exception e){} } } Output: child
  • 74. 74 /*Case: subclass overridden method declares subclass exception*/ import java.io.*; class Parent{ void msg()throws Exception {System.out.println("parent");} } class TestExceptionChild4 extends Parent{ void msg()throws ArithmeticException {System.out.println("child");} public static void main(String args[]){ Parent p=new TestExceptionChild4(); try{ p.msg(); }catch(Exception e){} } } Output: child /*Case: subclass overridden method declares no exception*/ import java.io.*; class Parent{ void msg()throws Exception {System.out.println("parent");} } class TestExceptionChild5 extends Parent { void msg() {System.out.println("child");} public static void main(String args[]){ Parent p=new TestExceptionChild5(); try{ p.msg(); }catch(Exception e){} } } Output: child