0% found this document useful (0 votes)
12 views

Module 4 - UA

Uploaded by

2022ishamshicrb
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Module 4 - UA

Uploaded by

2022ishamshicrb
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 88

Module 4

 A class which is declared with the abstract keyword is known as an


abstract class in Java. It can have abstract and non-abstract
methods (method with the body).
 Abstraction is a process of hiding the implementation details and
showing only functionality to the user.
 Another way, it shows only essential things to the user and hides
the internal details, for example, sending SMS where you type the
Abstract class text and send the message. You don't know the internal processing
about the message delivery.
 Abstraction lets you focus on what the object does instead of
how it does it.
 There are two ways to achieve abstraction in java
 Abstract class
 Interface
abstract class class-name
{
non-abstract/regular methods
{
}
Abstract class abstract methods();
}
An abstract class may contain a mix of non-abstract
methods and abstract methods, or only abstract methods
or only non-abstract regular methods
Abstract class
• An abstract class must be declared with an abstract keyword.
• It can have abstract and non-abstract methods.
• It cannot be instantiated. An abstract class cannot be directly
instantiated with the new operator. Such objects would be
useless, because an abstract class is not fully defined.
• It can have constructors and static methods also.
• Cannot declare abstract constructors, or abstract static
methods.
• It can have final methods which will force the subclass not to
change the body of the method.
• If there is an abstract method in a class, that class must be
abstract.
• If you are extending an abstract class that has an abstract
method, you must either provide the implementation of the
method or make this class abstract.
Abstract
Method
• A method which is declared as abstract and does not have
in Java implementation is known as an abstract method.

abstract type name(parameter-list);


abstract void printStatus();
package examplejava;
abstract class Bank{
abstract int getRateOfInterest();
Abstract }
class SBI extends Bank{
int getRateOfInterest(){ return 7;}
Method }
class PNB extends Bank{
int getRateOfInterest(){return 8;}
in Java }
class Abstracct_demo{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("Rate of Interest is:
"+b.getRateOfInterest()+" %");
b=new PNB();
System.out.println("Rate of Interest is:
"+b.getRateOfInterest()+" %");

}
} OUTPUT:
Rate of Interest is: 7 %
Rate of Interest is: 8 %
• Packages are containers for classes that are used to
keep the class name space compartmentalized.
• For example, a package allows you to create a class
named List, which you can store in your own package
without concern that it will collide with some other
class named List stored elsewhere.
• Packages are stored in a hierarchical manner and are
explicitly imported into new class definitions.
• Java provides a mechanism for partitioning the class
Packages name space into more manageable chunks. This
mechanism is the package.
• The package is both a naming and a visibility control
mechanism.
• You can define classes inside a package that are not
accessible by code outside that package.
• Preventing naming conflicts.
• For example there can be two classes with name
Employee in two packages,
college.staff.cse.Employee and
college.staff.ee.Employee
• Making searching/locating and usage of classes, interfaces,
enumerations and annotations easier
Packages are • Providing controlled access: protected and default have
package level access control.
used for, • A protected member is accessible by classes in the same
package and its subclasses. A default member (without any
access specifier) is accessible by classes in the same package
only.
• Packages can be considered as data encapsulation (or data-
hiding).
• Include a package command as the first statement in a Java
source file.
• Any classes declared within that file will belong to the specified
package.
• The package statement defines a name space in which classes are
stored.
• If you omit the package statement, the class names are put into
the default package, which has no name.
• Syntax: package pkg;
Here, pkg is the name of the package.
package MyPackage;
• 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.

• More than one file can include the same package statement.
• 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.
Defining a package pkg1[.pkg2[.pkg3]];
Package package java.awt.image;
• needs to be stored in java\awt\image in a
Windows environment.
Two types
1. Built-in Packages
java.lang: Contains language support classes
Types of java.io: Contains classed for supporting input /
packages output operations.
java.applet: Contains classes for creating
Applets.
2. User-defined packages
These are the packages that are defined by the
user.
• How does the Java run-time system know where to
look for packages that you create?
• The answer has three parts.
• First, by default, the Java run-time system uses the
Finding current working directory as its starting point. Thus,
if your package is in a subdirectory of the current
Packages and directory, it will be found.
CLASSPATH • Second, you can specify a directory path or paths
by setting the CLASSPATH environmental variable.
• Third, you can use the -classpath option with
java and javac to specify the path to your classes.
• When the second two options are used, the
class path must not include MyPack, itself.
• It must simply specify the path to MyPack.
Finding • For example, in a Windows environment, if the
Packages and path to MyPack is
CLASSPATH
C:\MyPrograms\Java\MyPack
• Then the class path to MyPack is
C:\MyPrograms\Java
• 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
Access • Java addresses four categories of visibility for class
Protection members:
– Subclasses in the same package
– Non-subclasses in the same package
– Subclasses in different packages
– Classes that are neither in the same package nor subclasses
for data and code.
Same Different
Same Difference
Access package package
Same class package Package
Modifier non- non-
subclass subclass
subclass subclass

Default Yes Yes Yes No No

Private Yes No No No No

Protected Yes Yes Yes Yes No

Public Yes Yes Yes Yes Yes


//This is file Protection.java:
package p1;
public class Protection {
int n = 1;
private int n_pri = 2;
protected int n_pro = 3;
public int n_pub = 4;
public Protection() {
System.out.println("base constructor");
System.out.println("n = " + n);
System.out.println("n_pri = " + n_pri);
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub);
}
}
//This is file Derived.java:
package p1;
class Derived extends Protection {
Derived() {
System.out.println("derived constructor");
System.out.println("n = " + n);
// System.out.println("n_pri = "4 + n_pri);
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub);
}
}
//This is file SamePackage.java:
package p1;
class SamePackage {
SamePackage() {
Protection p = new Protection();
System.out.println("same package constructor");
System.out.println("n = " + p.n);
// System.out.println("n_pri = " + p.n_pri);
System.out.println("n_pro = " + p.n_pro);
System.out.println("n_pub = " + p.n_pub);
}
}
// Demo package p1.
package p1;
// Instantiate the various classes in p1.
public class Demo {
public static void main(String args[]) {
Protection ob1 = new Protection();
Derived ob2 = new Derived();
SamePackage ob3 = new SamePackage();
}
}
//This is file Protection2.java:
package p2;
class Protection2 extends p1.Protection {
Protection2() {
System.out.println("derived other package constructor");
// class or package only
// System.out.println("n = " + n);
// class only
// System.out.println("n_pri = " + n_pri);
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub);
}
}
This is file OtherPackage.java:
package p2;
class OtherPackage {
OtherPackage() {
p1.Protection p = new p1.Protection();
System.out.println("other package constructor");
// class or package only
// System.out.println("n = " + p.n);
// class only
// System.out.println("n_pri = " + p.n_pri);
// class, subclass or package only
// System.out.println("n_pro = " + p.n_pro);
System.out.println("n_pub = " + p.n_pub);
}
}
// Demo package p2.
package p2;
// Instantiate the various classes in p2.
public class Demo {
public static void main(String args[]) {
Protection2 ob1 = new Protection2();
OtherPackage ob2 = new OtherPackage();
}
}
• Java includes the import statement to bring certain classes, or entire
packages, into visibility.
• Once imported, a class can be referred to directly, using only its name.
• The import statement is a convenience to the programmer and is not
technically needed to write a complete Java program.
• In a Java source file, import statements occur immediately following
the package statement (if it exists) and before any class definitions.
Importing import pkg1[.pkg2].(classname*);
• Here, pkg1 is the name of a top-level package, and pkg2 is the name
Packages of a subordinate package inside the outer package separated by a
dot (.).
• There is no practical limit on the depth of a package hierarchy, except
that imposed by the file system.
• Specify either an explicit classname or a star (*), which indicates that
the Java compiler should import the entire package.
import java.util.Date;
import java.io.*;
• If you import a package, subpackages will not be
imported.
• There are three ways to access the package from
outside the package.
Importing 1. import package.*;
Packages 2. import package.classname;
3. fully qualified name.
import package.*;

//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();
}
}

Output:Hello
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}

import //save by B.java


package mypack;
package. import pack.A;
classname; class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}

Output:Hello
//save by A.java package
pack; public class A{
public void msg(){System.out.println("Hello");}
}

//save by B.java
package mypack;
fully qualified
name class B{
public static void main(String args[]){
pack.A obj = new pack.A(); // using fully qualified name
obj.msg();
}
}

OUTPUT:Hello
fully qualified name
import java.util.*;
class MyDate extends Date {
}

The same example without the import statement looks


like this:

class MyDate extends java.util.Date {


}
Example of Subpackage

package com.javatpoint.core;
class Simple{
public static void main(String args[]){
System.out.println("Hello subpackage");
}
}

To Compile: javac -d . Simple.java


To Run: java com.javatpoint.core.Simple
Output:Hello subpackage
How to send the class file to another directory or drive
//save as Simple.java package
mypack; public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}

To Compile:
e:\sources> javac -d c:\classes Simple.java
To Run:
To run this program from e:\source directory, you need to set
classpath of the directory where the class file resides.
e:\sources> set classpath=c:\classes;.;
e:\sources> java mypack.Simple
Another way to run this program by -classpath switch of java:
e:\sources> java -classpath c:\classes mypack.Simple
Ways to load the class files or jar files

There are two ways to load the class files


temporary and permanent
•Temporary
•By setting the classpath in the command prompt
•By -classpath switch
•Permanent
•By setting the classpath in the environment variables
•By creating the jar file, that contains all the class files,
and copying
the jar file in the jre/lib/ext folder.
• Interfaces: Definition, Implementing Interfaces, Extending
Interfaces, Nested Interfaces, Applying Interfaces,
Variables in Interfaces.
Interfaces
• Using the keyword interface, you can fully abstract a class’
interface from its implementation.
• That is, using interface, you can specify what a class must do,
but not how it does it.
• Interfaces are syntactically similar to classes, but they lack
instance variables, and their methods are declared without
any body.
• Once it is defined, any number of classes can implement an
interface. Also, one class can implement any number of
interfaces.
• “one interface, multiple methods” aspect of polymorphism.
• Interfaces are designed to support dynamic method
resolution at run time.
• Interfaces add most of the functionality that is required for
many applications that would normally resort to using
multiple inheritance.
Interfaces
• An interface in Java is a blueprint of a class.
• It has static constants and abstract methods.
• The interface in Java is a mechanism to
achieve abstraction.
• There can be only abstract methods in the Java
interface, not method body. It is used to achieve
abstraction and multiple inheritance in Java.
• Interfaces can have abstract methods and variables. It
cannot have a method body.
• Java Interface also represents the IS-A relationship.
• It cannot be instantiated just like the abstract class.
Use of Interfaces
• There are mainly three reasons to use interface.
1. It is used to achieve abstraction.
2. By interface, we can support the functionality of multiple
inheritance.
3. It can be used to achieve loose coupling.
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);
type final-varnameN = value;
}

The Java compiler adds public and abstract keywords before the interface method.
Moreover, it adds public, static and final keywords before data members.
The relationship between classes and
interfaces

class classname [extends superclass] [implements interface [,interface...]] {


// class-body
}
interface printable{ OUTPUT
void print(); Hello

}
class IntfEx implements printable{
public void print()
{
System.out.println("Hello");
}
public static void main(String args[]){
IntfEx obj = new IntfEx();
obj.print();
}
}
Accessing Implementations Through Interface
References
• You can declare variables as object references that use an interface
rather than a class type.
• Any instance of any class that implements the declared interface can
be referred to by such a variable. When you call a method through
one of these references, the correct version will be called based on
the actual instance of the interface being referred to. This is one of
the key features of interfaces.
• The method to be executed is looked up dynamically at run time,
allowing classes to be created later than the code which calls
methods on them. The calling code can dispatch through an
interface without having to know anything about the “callee.”
• This process is similar to using a superclass reference to access a
subclass object.
interface Drawable{
void draw();
Output:
} drawing circle
class Rectangle implements Drawable{
public void draw(){
System.out.println("drawing rectangle");
}
}
class Circle implements Drawable{
public void draw(){
System.out.println("drawing circle");
}
}
class TestInterface1{
public static void main(String args[]){
Drawable d=new Circle();
d.draw();
}}
interface Bank{
float rateOfInterest(); Output:
} ROI: 9.15
class SBI implements Bank{
public float rateOfInterest(){
return 9.15f;
}
}
class PNB implements Bank{
public float rateOfInterest(){
return 9.7f;
}
}
class TestInterface2{
public static void main(String[] args){
Bank b=new SBI();
System.out.println("ROI: "+b.rateOfInterest());
}}
Multiple inheritance in Java by interface

1) Multiple inheritance is not supported through class in java, but it is possible by an


interface, why?
Ans:- Multiple inheritance is not supported in the case of class because of ambiguity.
However, it is supported in case of an interface because there is no ambiguity. It is
because its implementation is provided by the implementation class.
interface Printable{
void print();
} Output:
interface Showable{ Hello Welcome
void show();
}
class IntfEx implements Printable,Showable{
public void print(){
System.out.println("Hello");}
public void show(){
System.out.println("Welcome");}

public static void main(String args[]){


IntfEx obj = new IntfEx();
obj.print();
obj.show();
}
}
Nested Interfaces
• An interface can be declared a member of a class or
another interface. Such an interface is called a member
interface or a nested interface.
• A nested interface can be declared as public, private, or
protected. This differs from a top-level interface, which
must either be declared as public or use the default access
level.
• When a nested interface is used outside of its enclosing
scope, it must be qualified by the name of the class or
interface of which it is a member.
• Thus, outside of the class or interface in which a nested
interface is declared, its name must be fully qualified.
Syntax of nested interface

which is declared within the which is declared within


interface the class
// A nested interface example within the class.
// This class contains a member interface.
class A {
// this is a nested interface
public interface NestedIF {
boolean isNotNegative(int x);
}
}
// B implements the nested interface.
class B implements A.NestedIF {
public boolean isNotNegative(int x) {
return x < 0 ? false : true;
}
}
class NestedIFDemo {
public static void main(String args[]) {
// use a nested interface reference
A.NestedIF nif = new B();
if(nif.isNotNegative(10))
System.out.println("10 is not negative");
if(nif.isNotNegative(-12))
System.out.println("this won't be displayed");
}
}
// nested interface which is declared within the interface

interface Showable{
void show();
interface Message{
void msg();
}
}
class TestNestedInterface1 implements Showable.Message{
public void msg(){
System.out.println("Hello nested interface");
}

public static void main(String args[]){


Showable.Message message=new TestNestedInterface1(); //upcasting here
message.msg();
}
}

Output:
hello nested interface
Applying Interfaces

// Define an integer stack interface. // Pop an item from the stack


interface IntStack { public int pop() {
void push(int item); // store an item if(tos < 0) {
int pop(); // retrieve an item System.out.println("Stack underflow.");
} return 0;
// IntStack that uses fixed storage. }
class FixedStack implements IntStack { else
private int stck[]; return stck[tos--];
private int tos; }
FixedStack(int size) { }
stck = new int[size];
tos = -1;
}
// Push an item onto the stack
public void push(int item) {
if(tos==stck.length-1)
System.out.println("Stack is full.");
else
stck[++tos] = item;
}
class IFTest {
public static void main(String args[]) {
FixedStack mystack1 = new FixedStack(5);
FixedStack mystack2 = new FixedStack(8);
// push some numbers onto the stack
for(int i=0; i<5; i++)
mystack1.push(i);
for(int i=0; i<8; i++)
mystack2.push(i);
// pop those numbers off the stack
System.out.println("Stack in mystack1:");
for(int i=0; i<5; i++)
System.out.println(mystack1.pop());
System.out.println("Stack in mystack2:");
for(int i=0; i<8; i++)
System.out.println(mystack2.pop());
}
}
Variables in Interfaces
• importing the constant fields into the class
name space as final variables.
interface SharedConstants {
int NO = 0;
int YES = 1;
int MAYBE = 2;
int LATER = 3;
int SOON = 4;
int NEVER = 5;
}
Interfaces Can Be Extended
// One interface can extend another. class IFExtend {
interface A { public static void main(String arg[]) {
void meth1(); MyClass ob = new MyClass();
void meth2(); ob.meth1();
} ob.meth2();
interface B extends A { ob.meth3();
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().");
}
}
Exception handling - Fundamentals
• An exception is an abnormal condition that arises in a code
sequence at run time. In other words, an exception is a run-
time error.
• When an exceptional condition arises, an object representing
that exception is created and thrown in the method that caused
the error. That method may choose to handle the exception
itself, or pass it on. Either way, at some point, the exception is
caught and processed.
• Exceptions can be generated by the Java run-time system, or
they can be manually generated by your code.
• In Java, an exception is an event that disrupts the normal
flow of the program. It is an object which is thrown at
runtime.
• Exception Handling is a mechanism to handle runtime errors
such as ClassNotFoundException, IOException, SQLException,
RemoteException, etc.
• Java exception handling is managed via five keywords: try,
catch, throw, throws, and finally.
• Program statements that you want to monitor for exceptions
are contained within a try block.
• If an exception occurs within the try block, it is thrown.
• Your code can catch this exception (using catch) and handle
it in some rational manner.
• System-generated exceptions are automatically thrown by
the Java run-time system.
• To manually throw an exception, use the keyword throw.
• Any exception that is thrown out of a method must be
specified as such by a throws clause.
Any code that absolutely must be executed after a try block completes is put in a
finally block.
try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...
finally {
// block of code to be executed after try block ends
}
Exception types
• All exception types are subclasses of the built-in
class Throwable.
• Thus, Throwable is at the top of the exception
class hierarchy.
• The java.lang.Throwable class is the root class of
Java Exception hierarchy which is inherited by
two subclasses:
1. Exception
2. Error
• There are mainly two types of
exceptions:
1. checked and
2. unchecked.
• Here, an error is considered as
the unchecked exception
• Checked Exception
– The classes which directly inherit Throwable class except
RuntimeException and Error are known as checked exceptions
e.g. IOException, SQLException etc.
– Checked exceptions are checked at compile-time.
• Unchecked Exception
– The classes which inherit RuntimeException are known as
unchecked exceptions e.g. ArithmeticException,
NullPointerException, ArrayIndexOutOfBoundsException etc.
– Unchecked exceptions are not checked at compile-time, but
they are checked at runtime.
• Error
– Error is irrecoverable e.g. OutOfMemoryError,
VirtualMachineError, AssertionError etc.
What happens when you don’t
handle exceptions

class Exc0 {
public static void main(String args[]) {
int d = 0;
int a = 42 / d;
}
}
Error Message:
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, haven’t supplied any exception handlers, so the
exception is caught by the default handler provided by the Java run-
time system.
• Any exception that is not caught by your program will ultimately be
processed by the default handler.
• The default handler displays a string describing the exception, prints a
stack trace from the point at which the exception occurred, and
terminates the program.
stack trace
The stack trace will always show the sequence of method invocations
that led up to the error.
The stack trace contains all invocations from the start of a thread until
the point it's generated. This is usually a position at which an exception
takes place. For example:

class Exc1 {
static void subroutine() { int d = 0; The resulting stack trace from the default exception
handler:
int a = 10 / d;
} java.lang.ArithmeticException: / by zero at
public static void main(String args[]) { Exc1.subroutine(Exc1.java:4)
at Exc1.main(Exc1.java:7)
Exc1.subroutine();
}
}
Using try and catch
• Handle an exception
– First, it allows you to fix the error.
– Second, it prevents the program from
automatically terminating.
• To guard against and handle a run-time error,
simply enclose the code that you want to
monitor inside a try block.
• Immediately following the try block, include a
catch clause that specifies the exception type
that you wish to catch.
try {
11block of code to monitor for errors

}
catch (ExceptionTypel el ) {
II exception handler for Exception'J'ypel
}
catch (ExceptionType2 e2) {
II exception handler for Exception1'ype2
}
II ..•
finally {
II block of code to be executed before try block
ends
}
package examplejava;

public class Except1 {


public static void main(String args[]) {
int d, a;
try {
d = 0;
a = 42 / d;
System.out.println("This will not be
printed.");
} catch (ArithmeticException e) {
System.out.println("Division by zero.");
}
System.out.println("After catch
statement.");
}
}
OUTPUT:
Division by zero.
After catch statement
• The call to println( ) inside the try block is never executed.
Once an exception is thrown, program control transfers out of
the try block into the catch block.
• Put differently, catch is not “called,” so execution never
“returns” to the try block from a catch.
• Thus, the line “This will not be printed.” is not displayed.
Once the catch statement has executed, program control
continues with the next line in the program following the
entire try/catch mechanism.
• A try and its catch statement form a unit.
• The scope of the catch clause is restricted to those statements
specified by the immediately preceding try statement.
• A catch statement cannot catch an exception thrown by another
try statement
• The statements that are protected by try must be surrounded by
curly braces.
• You cannot use try on a single statement.
• Throwable overrides the toString( ) method (defined by Object).
Multiple catch Clauses
• In some cases, more than one exception could be
raised by a single piece of code.
• To handle this type of situation, you can specify
two or more catch clauses, each catching a
different type of exception.
• When an exception is thrown, each catch
statement is inspected in order, and the first one
whose type matches that of the exception is
executed.
• After one catch statement executes, the others are
bypassed, and execution continues after the
try/catch block.
package examplejava;
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.");
}
}
}
/* The above 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 Statements
• The try statement can be nested. That is, a try statement can
be inside the block of another try.
• Each time a try statement is entered, the context of that
exception is pushed on the stack.
• If an inner try statement does not have a catch handler for a
particular exception, the stack is unwound and 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.
// An example of nested try statements.
class NestTry {
public static void main(String args[]) {
try {
int a = args.length;
/* If no command-line args are present */
int b = 42 / a;
System.out.println("a = " + a);
try { // nested try block
/* If one command-line arg is used */
if(a==1)
a = a/(a-a); // division by zero
/* If two command-line args are used */
if(a==2) {
int c[] = { 1 };
c[42] = 99; // generate an out-of-bounds exception
}
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out-of-bounds: " + e);
}
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
}}
throw

• catching exceptions that are thrown automatically by the Java run-


time system.
• However, it is possible to throw an exception explicitly, using the
throw statement.
throw ThrowableInstance;
• Here, ThrowableInstance must be an object of type Throwable or a
subclass of Throwable. Primitive types (int or char), as well as non-
Throwable classes, such as String and Object, cannot be used as
exceptions.
• There are two ways you can obtain a Throwable object:
– using a parameter in a catch clause, or
– creating one with the new operator.
• 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 exception.
• If it does find a match, control is transferred to that
statement. If not, then the next enclosing try statement
is inspected, and so on.
• If no matching catch is found, then the default
exception handler halts the program and prints the
stack trace.
package examplejava;
//Demonstrate throw.
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);
}
}
}
This program gets two chances to deal with the same
error.
First, main( ) sets up an exception context and then calls
demoproc( ).
The demoproc( ) method then sets up another exception handling
context and immediately throws a new instance of
NullPointerException, which is caught on the next line.
The exception is then rethrown.

output:
Caught inside demoproc.
Recaught: java.lang.NullPointerException: demo
throws
• 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.
• You do this by including a throws clause in the method’s declaration.
• A throws clause lists the types of exceptions that a method might
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.
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.

public static void main(String args[])throws NullPointerException,


ArithmeticException
{
try{
throw new NullPointerExcption();
System.out.println(“aaaaaaaa”); //unreachable code
}
catch(ArithmeticException a){ }
}
// 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();
// 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);
}
}
}
finally
• When exceptions are thrown, execution in a method
takes a rather abrupt, nonlinear path that alters the
normal flow through the method.
• Depending upon how the method is coded, it is even
possible for an exception to cause the method to
return prematurely.
• This could be a problem in some methods.
• For example, if a method opens a file upon entry and
closes it upon exit, then you will not want the code
that closes the file to be bypassed by the exception-
handling mechanism.
• The finally keyword is designed to address this
contingency.
finally
• finally creates a block of code that will be executed after a
try/catch block has completed and before the code following the
try/catch block.
• The finally block will execute whether or not an exception is
thrown. 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.
• This can be useful for closing file handles and freeing up any
other resources that might have been allocated at the beginning
of a method with the intent of disposing of them before
returning.
• The finally clause is optional.
• However, each try statement requires at least one catch or a
finally clause.
// Execute a try block normally. static void procC()
/// Demonstrate finally. {
class FinallyDemo { //Through an exception out of the method. try {
static void procA() { System.out.println("inside procC");
try { } finally {
System.out.println("inside procA"); System.out.println("procC's finally");
throw new RuntimeException("demo"); }
} finally { }
System.out.println("procA's finally"); public static void main(String args[]) {
} try {
} procA();
// Return from within a try block. } catch (Exception e) {
static void procB() { System.out.println("Exception caught");
try { }
System.out.println("inside procB"); return; procB();
} finally { procC();
System.out.println("procB's finally"); }
} }
}

You might also like