Presentation is loading. Please wait.

Presentation is loading. Please wait.

G. Pullaiah College of Engineering and Technology

Similar presentations


Presentation on theme: "G. Pullaiah College of Engineering and Technology"— Presentation transcript:

1 G. Pullaiah College of Engineering and Technology
Object Oriented Programming through Java Department of Computer Science & Engineering

2 UNIT III 1. Inheritance 2. Packages 3. Interfaces 4. Exception Handling

3 Inheritance On the surface, inheritance is a code re-use issue.
we can extend code that is already written in a manageable manner. Inheritance is more it supports polymorphism at the language level

4 Inheritance Take an existing object type (collection of fields and methods) and extend it. create a special version of the code without re-writing any of the existing code (or even explicitly calling it!). End result is a more specific object type, called the sub- class / derived class / child class. The original code is called the superclass / parent class / base class.

5 Inheritance Example Employee: name, email, phone
FulltimeEmployee: also has salary, office, benefits, … Manager: CompanyCar, can change salaries, rates contracts, offices, etc. Contractor: HourlyRate, ContractDuration, … A manager is a special kind of FullTimeEmployee, which is a special kind of Employee.

6 Polymorphism Create code that deals with general object types, without the need to know what specific type each object is. Generate a list of employee names: all objects derived from Employee have a name field since Employee has a name field no need to treat managers differently from anyone else.

7 Method Polymorphism The real power comes with methods/behaviors.
A better example: shape object types used by a drawing program. we want to be able to handle any kind of shape someone wants to code (in the future). we want to be able to write code now that can deal with shape objects (without knowing what they are!).

8 Shapes Shape: color, layer fields draw() draw itself on the screen
calcArea() calculates it's own area. serialize() generate a string that can be saved and later used to re-generate the object.

9 Kinds of Shapes Rectangle Triangle Circle
Each could be a kind of shape (could be specializations of the shape class). Each knows how to draw itself, etc. Could write code to have all shapes draw themselves, or save the whole collection to a file.

10 class definition class classname { field declarations
{ initialization code } Constructors Methods }

11 Abstract Class modifier
Abstract modifier means that the class can be used as a superclass only. no objects of this class can be created. can have attributes, even code all are inherited methods can be overridden Used in inheritance hierarchies

12 Interesting Method Modifiers
private/protected/public: protected means private to all but subclasses what if none of these specified? abstract: no implementation given, must be supplied by subclass. the class itself must also be declared abstract final: the method cannot be changed by a subclass (no alternative implementation can be provided by a subclass).

13 Interesting Method Modifiers
(that have nothing to do with this slide set) native: the method is written in some local code (C/C++) - the implementation is not provided in Java (recall assembler routines linked with C) synchronized: only one thread at a time can call the method (later)

14 Inheritance vs. Composition
When one object type depends on another, the relationship could be: is-a has-a Sometimes it's hard to define the relationship, but in general you use composition (aggregation) when the relationship is has-a

15 Composition One class has instance variables that refer to object of another. Sometimes we have a collection of objects, the class just provides the glue. establishes the relationship between objects. There is nothing special happening here (as far as the compiler is concerned).

16 Inheritance One object type is defined as being a special version of some other object type. a specialization. The more general class is called: base class, super class, parent class. The more specific class is called: derived class, subclass, child class.

17 Inheritance A derived class object is an object of the base class.
is-a, not has-a. all fields and methods are inherited. The derived class object also has some stuff that the base class does not provide (usually).

18 Java Inheritance Two kinds:
implementation: the code that defines methods. interface: the method prototypes only. Other OOP languages often provide the same capabilities (but not as an explicit option).

19 Implementation Inheritance
Derived class inherits the implementations of all methods from base class. can replace some with alternatives. new methods in derived class can access all non-private base class fields and methods. This is similar to (simple) C++ inheritance.

20 Accessing superclass methods from derived class.
Can use super() to access all (non-private) superclass methods. even those replaced with new versions in the derived class. Can use super() to call base class constructor. use arguments to specify desired constructor

21 Single inheritance only (implementation inheritance).
You can't extend more than one class! the derived class can't have more than one base class. You can do multiple inheritance with interface inheritance.

22 Casting Objects A object of a derived class can be cast as an object of the base class. this is much of the power! When a method is called, the selection of which version of method is run is totally dynamic. overridden methods are dynamic. Note: Selection of overloaded methods is done at compile time. There are some situations in which this can cause confusion.

23 The class Object Granddaddy of all Java classes.
All methods defined in the class Object are available in every class. Any object can be cast as an Object.

24 Interfaces An interface is a definition of method prototypes and possibly some constants (static final fields). An interface does not include the implementation of any methods, it just defines a set of methods that could be implemented.

25 interface implementation
A class can implement an interface, this means that it provides implementations for all the methods in the interface. Java classes can implement any number of interfaces (multiple interface inheritance).

26 Interfaces can be extended
Creation (definition) of interfaces can be done using inheritance: one interface can extend another. Sometimes interfaces are used just as labeling mechanisms: Look in the Java API documentation for interfaces like Cloneable. Example: BubbleSort w/ SortInterfaceDemo

27 Abstract Classes Java allows abstract classes
use the modifier abstract on a class header to declare an abstract class abstract class Vehicle { … } An abstract class is a placeholder in a class hierarchy that represents a generic concept Vehicle Car Boat Plane

28 Abstract Class: Example
An abstract class often contains abstract methods, though it doesn’t have to Abstract methods consist of only methods declarations, without any method body public abstract class Vehicle { String name; public String getName() { return name; } \\ method body abstract public void move(); \\ no body! }

29 Abstract Classes An abstract class often contains abstract methods, though it doesn’t have to Abstract methods consist of only methods declarations, without any method body The non-abstract child of an abstract class must override the abstract methods of the parent An abstract class cannot be instantiated (why?) The use of abstract classes is a design decision; it helps us establish common elements in a class that is too general to instantiate

30 Recap: Object References
All interaction with an object occurs through object reference variables An object reference variable holds the reference (address, the location) of an object ChessPiece bishop1 = new ChessPiece(); bishop1

31 Recap: Primitive Assignment
The act of assignment takes a copy of a value and stores it in a variable For primitive types: num2 = num1; Before num1 5 num2 12 After num1 5 num2

32 Recap: Reference Assignment
For object references, the reference is copied: bishop2 = bishop1; Before bishop1 bishop2 After bishop1 bishop2

33 Recap: Relationship Between Objects and Object References
Two or more references can refer to the same object; these references are called aliases of each other One object (and its data) can be accessed using different references

34 References and Inheritance
An object reference can refer to an object of its class, or to an object of any class derived from it by inheritance For example, if the Holiday class is used to derive a child class called Christmas, then a Holiday reference could actually be used to point to a Christmas object Holiday Holiday day; day = new Holiday(); day = new Christmas(); Christmas

35 References and Inheritance
Assigning an object to an ancestor reference is considered to be a widening conversion, and can be performed by simple assignment Assigning an ancestor object to a reference can also be done, but it is considered to be a narrowing conversion and must be done with a cast The widening conversion is the most useful for implementing polymorphism Holiday day = new Christmas(); Christmas c1 = new Christmas(); Holiday day = c1; Christmas c2 = (Christmas) day;

36 Recap: References and Inheritance
An object reference variable can refer to any object instantiated from its own class, or any class derived from it by inheritance For example, Holiday Holiday day; day = new Holiday(); day = new Christmas(); Christmas The assignment of an object of a derived class to a reference variable of the base class can be considered as a widening conversion

37 References and Inheritance
Through a given type of reference variable, we can invoke only the methods defined in that type class Holiday { public void celebrate() {…} } class Christmas extends Holiday { public void celebrate() {…} public void listenToChristmasSongs() {…} } Holiday day; day = new Christmas(); Can we do the following statements: day.celebrate(); day.listenToChristmasSongs();

38 References and Inheritance
We can “promote” an object back to its original type through an explicit narrowing cast: Holiday day = new Christmas(); day.celebrate(); Christmas c = (Christmas) day; c.listenToChristmasSongs(); Question: which celebrate() will be invoked by the line: day.celebrate();

39 What is Polymorphism? A polymorphic reference can refer to different types of objects at different times In java every reference can be polymorphic except of references to base types and final classes. It is the type of the object being referenced, not the reference type, that determines which method is invoked Polymorphic references are therefore resolved at run-time, not during compilation; this is called dynamic binding Careful use of polymorphic references can lead to elegant, robust software designs

40 Polymorphism Polymorphism: A polymorphic reference v is declared as class C, but unless C is final or base type, v can refer to an object of class C or to an object of any class derived from C. A method call v.<method_name>(<args>) invokes a method of the class of an object referred to by v (not necessarily C): A very common usage of polymorphism: If classes C1, C2, ...., Cn are all derived from C, define an array A of elements of C. The entries A[i] can then refer to objects of classes C1, ...., Cn. Ex2: void process(Holiday day) { … day.celebrate(); … } Christmas day = ...; process(day) Ex1: Holiday day = new Christmas(); day.celebrate();

41 Method payday() also calls println(s) on each s.
The pay-roll of a firm - staffList: staffMemeber[] Staff + payday() : void - staffList : StaffMemeber[] StaffMember # name : String # address : String # phone : String + toString() : String + pay() : double Method payday() also calls println(s) on each s. This works because println is defined as: void println(Object o) {String s =o.toString()); OutStream.out(s); } Method payday() iterates over elements s of staffList and calls s.pay() on each s. Employee # socialSecurityNumber : String # payRate : double + toString() : String + pay() : double Volunteer + pay() : double Executive - bonus : double + awardBonus(execBonus : double) : void + pay() : double Hourly - hoursWorked : int + addHours(moreHours : int) : void + toString() : String + pay() : double

42 Single vs. Multiple Inheritance
Some object-oriented languages allow multiple inheritance, which allows a class to be derived from two or more classes, inheriting the members of all parents The price: collisions, such as the same variable name, same method name in two parents, have to be resolved Java decision: single inheritance, meaning that a derived class can have only one parent class

43 Java Interface A Java interface is a collection of constants and abstract methods abstract method: a method header without a method body; we declare an abstract method using the modifier abstract since all methods in an interface are abstract, the abstract modifier is usually left off Methods in an interface have public visibility by default

44 Interface: Syntax interface is a reserved word public interface Doable
{ public static final String NAME; public void doThis(); public int doThat(); public void doThis2 (float value, char ch); public boolean doTheOther (int num); } A semicolon immediately follows each method header No method in an interface has a definition (body)

45 Implementing an Interface
A class formally implements an interface by stating so in the class header in the implements clause a class can implement multiple interfaces: the interfaces are listed in the implements clause, separated by commas If a class asserts that it implements an interface, it must define all methods in the interface or the compiler will produce errors

46 Implementing Interfaces
public class Something implements Doable { public void doThis () // whatever } public void doThat () // etc. implements is a reserved word Each method listed in Doable is given a definition public class ManyThings implements Doable, AnotherDoable

47 Interfaces: An Example
A class that implements an interface can implement other methods as well

48 <<interface>>
UML Diagram <<interface>> Complexity + getComplexity () : int + setComplexity (int) : void MiniQuiz + main(args : String[]) : void 1 2 Question + getQuestion () : String + getAnswer () : String + answerCorrect (String) : boolean + toString() : String

49 Interfaces: Examples from Java Standard Class Library
The Java Standard Class library defines many interfaces: the Iterator interface contains methods that allow the user to move through a collection of objects easily hasNext(), next(), remove() the Comparable interface contains an abstract method called compareTo, which is used to compare two objects if (obj1.compareTo(obj2) < 0) System.out.println(“obj1 is less than obj2”);

50 Polymorphism via Interfaces
Define a polymorphism reference through interface declare a reference variable of an interface type Doable obj; the obj reference can be used to point to any object of any class that implements the Doable interface the version of doThis depends on the type of object that obj is referring to: obj.doThis();

51 Example: Polymorphism via Interface
The payroll program revisited: we want to sort the employees by name

52 More Examples Speaker guest; guest = new Philosopher(); guest.speak();
guest = Dog(); public interface Speaker { public void speak(); } class Philosopher extends Human implements Speaker // public void speak() {…} public void pontificate() {…} class Dog extends Animal implements Speaker public void speak() { Speaker special; special = new Philosopher(); special.pontificate(); // compiler error Speaker special; special = new Philosopher(); ((Philosopher)special).pontificate();

53 Interface Hierarchies
Inheritance can be applied to interfaces as well as classes One interface can be used as the parent of another The child interface inherits all abstract methods of the parent A class implementing the child interface must define all methods from both the parent and child interfaces Note that class hierarchies and interface hierarchies are distinct (they do not overlap)

54 What is Package? A package is a collection of related classes and interfaces providing access protection and namespace management. To make classes easier to find and to use To avoid naming conflicts To control access

55 Why Using Packages? Programmers can easily determine that these classes and interfaces are related. Programmers know where to find classes and interfaces that provide graphics-related functions. The names of classes won’t conflict with class names in other packages, because the package creates a new namespace. Allow classes within the package to have unrestricted access to one another yet still restrict access for classes outside the package

56 Put Your Classes and Interfaces into Packages
It is no need to “create” packages, they come to existence as soon as they are declared The first line of your source file: package <package_name>; e.g. package cars; class Car { … } Every class must belong to one package. Only one package statement is allowed per source file. If package statement is omitted, the class belongs to a special default package – the only package in Java that has no name.

57 Subpackages We can create hierarchies of nested packages e.g.
package machines.vehicles.cars; class FastCar extends Car {…} Subpackage names must always be prefixed with names of all enclosing packages. Package hierarchy does not have a single top-level all-encompassing root package.Instead, we deal with a collection of top-level packages

58 Partial Package Tree of Java
lang String Math reflect Constructor Method awt Frame Button io ObjectInputStream ObjectOutputStream util Vector Random

59 Packages and Class Packages subdivide name space of Java classes
machines.vehicles.cars.FastCar mycar = new machine.vehicles.cars.FastCar(); Package names should be made as unique as possible to prevent name clashes Class name must be fully qualified with their package name. Except: Class name immediately following the class keyword, e.g. class Car{…} Class belongs to the same package as the class being currently defined Class is explicitly specified in one of the import statements Class belongs to java.lang package (all java.lang classes are implicitly imported)

60 import Statement To avoid typing fully qualified names – use import statements sandwiched between the package statement and class definition. e.g. package grand.prix; import java.lang.*; //implicitly specified import java.util.Random; import machines.vehicles.cars.*; import machines.*.*; //COMPILER ERROR! import Racer; //from default package class SuperFastCar extends FastCar { private Racer r; public static void main(String{[] args) Random RNG = new Random(); java.util.Vector v = new java.util.Vector(); }

61 Store Class Files Class files must be stored in a directory structure that mirrors package hierarchy e.g. Both .java and .class files for FastCar class from the machines.vehicles.cars package can be stored in the following directory: C:\A\B\classes\machines\vehicles\cars

62 Classpath Compiled classes can be stored in different locations in the file systems. How to locating these files – Setting a classpath which is a list of directories where class files should be searched e.g. If Java system is to find classes from the machines.vehicles.cars package , its classpath must point to C:\A\B\classes, the root of the package directory hierarchy.

63 Setup Classpath In command line
c:\> java –classpath C:\A\B\classes machines.vehicles.cars.Car To avoid specify the classpath in every command, set classpath as a command shell environment variable: Windows: >set CLASSPATH = C:\A\B\classes >set CLASSPATH = .; %CLASSPATH% >echo %CLASSPATH% .; C:\A\B\classes Unix: $CLASSPATH = $HOME/A/B/classes $CLASSPATH = .: $CLASSPATH $echo $CLASSPATH .: home/santa/A/B/classes

64 Classpath for .zip and .jar File
JDK can open .zip and .jar archives and search for class files inside. The archives must store class files within the appropriate directory structure. Set up classpath for archives: >set CLASSPATH = %CLASSPATH%;c:\user.jar

65 What's an Exception? exception is shorthand for the phrase "exceptional event." An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. Many kinds of errors can cause exceptions Hardware errors, like a hard disk crash, Programming errors, such as trying to access an out- of-bounds array element.

66 Process in Java When Errors Happen
When an error occurs within a Java method, the method creates an exception object and hands it off to the runtime system. The exception object contains information about the exception, including its type and the state of the program when the error occurred. The runtime system is responsible for finding some code to handle the error. Creating an exception object and handing it to the runtime system is called throwing an exception.

67 Why Using Exceptions? Java programs have the following advantages over traditional error management techniques: Separate error handling code from “regular” code. Propagate errors up the call stack Group error types and error differentiation

68 Separating Error Handling Code from "Regular" Code
In traditional programming, error detection, reporting and handling often lead to confusing code. A high rate of a bloat factor So much error detection, reporting and returning that the original code are lost in the clutter. The logical flow of the code has been lost in the clutter, making it difficult to tell if the code is doing the right thing: It's even more difficult to ensure that the code continues to do the right thing after you modify the function three months after writing it. Ignoring it?--errors are "reported" when their programs crash.

69 What happens if the file can't be opened?
e.g. The pseudo-code for a function that reads an entire file into memory might look like this: readFile { open the file; determine its size; allocate that much memory; read the file into memory; close the file; } It ignores all of these potential errors: What happens if the file can't be opened? What happens if the length of the file can't be determined? What happens if enough memory can't be allocated? What happens if the read fails? What happens if the file can't be closed?

70 errorCodeType readFile { initialize errorCode = 0; open the file; if (theFileIsOpen) { determine the length of the file; if (gotTheFileLength) { allocate that much memory; if (gotEnoughMemory) { read the file into memory; if (readFailed) errorCode = -1; } else errorCode = -2; else errorCode = -3; close the file; if (theFileDidntClose && errorCode == 0) errorCode = -4; else errorCode = errorCode and -4; else errorCode = -5; return errorCode;

71 Java solution: readFile { try open the file; determine its size;
allocate that much memory; read the file into memory; close the file; } catch (fileOpenFailed) {doSomething; } catch (sizeDeterminationFailed) catch (memoryAllocationFailed) catch (readFailed) { doSomething; } catch (fileCloseFailed)

72 Propagating Errors Up the Call Stack
Propagate error reporting up the call stack of methods. Suppose that the readFile method is the fourth method in a series of nested method calls: method1 calls method2, which calls method3, which finally calls readFile. method1 { call method2; } method2 { call method3; } method3 { call readFile; } Suppose that method1 is the only method interested in the errors that occur within readFile. Traditional error notification techniques force method2 and method3 to propagate the error codes returned by readFile up the call stack until the error codes finally reach method1--the only method that is interested in them.

73 method1 { errorCodeType error; error = call method2; if (error) doErrorProcessing; else proceed; } errorCodeType method2 error = call method3; return error; errorCodeType method3 error = call readFile;

74 Java solution: runtime system searches backwards through the call stack to find any methods that are interested in handling a particular exception. A Java method can "duck" any exceptions thrown within it, thereby allowing a method further up the call stack to catch it. method1 { try { call method2; } catch (exception) { doErrorProcessing; } } method2 throws exception { call method3; } method3 throws exception { call readFile; }

75 Grouping Error Types and Error Differentiation
Exceptions often fall into categories or groups. A group of exceptions: The index is out of range for the size of the array The element being inserted into the array is of the wrong type The element being searched for is not in the array. Some methods would like to handle all exceptions that fall within a category, and other methods would like to handle specific exceptions All exceptions that within a Java program are first- class objects, grouping or categorization of exceptions is a natural outcome of the class hierarchy.

76 Java exceptions must be instances of Throwable or any Throwable descendant.
You can create subclasses of the Throwable class and subclasses of your subclasses. Each "leaf" class (a class with no subclasses) represents a specific type of exception and each "node" class

77 Overview of Exception Hierarchy (1)
When an exceptional condition causes an exception to be thrown, that exception is an object derived, either directly, or indirectly from the class Throwable The Throwable class has two subclasses: Error: indicates that a non-recoverable error has occurred that should not be caught. Errors usually cause the Java interpreter to display a message and exit Exception: indicates an abnormal condition that must be properly handled to prevent program termination

78 Overview of Exception Hierarchy (2)
In JDK 1.1.3, there are nine subclasses of the Exception class, several of which have numerous subclasses. One subclass of Exception is the class named RuntimeException This class has eleven subclasses, some of which are further subclasses. All exceptions other than those in the RuntimeException class must be either caught declared (specified) in a throws clause of any method that can throw them.

79 Throwable Class Definition
public class java.lang.Throwable extends java.lang.Object { // Constructors public Throwable(); public Throwable(String message); // Methods public Throwable fillInStackTrace(); public String getMessage(); public void printStackTrace(); public void printStackTrace(PrintStream s); public String toString(); }

80 Runtime Exceptions Exceptions that occur within the Java runtime system. arithmetic exceptions (e.g. dividing by zero) pointer exceptions (e.g. trying to access an object through a null reference) indexing exceptions (e.g. attempting to access an array element through an index that is too large or too small). Runtime exceptions can occur anywhere in a program. The cost of checking for runtime exceptions often exceeds the benefit of catching or specifying them. Thus the compiler does not require catching or specifying runtime exceptions.

81 Some Terms in Exception Handling (1)
Catch: A method catches an exception by providing an exception handler for that type of exception object. Specify: If a method does not provide an exception handler for the type of exception object thrown, the method must specify (declare) that it can throw that exception. Any exception that can be thrown by a method is part of the method's public programming interface and users of a method must know about the exceptions that a method can throw. You must specify the exceptions that the method can throw in the method signature

82 Some Terms in Exception Handling (2)
Checked Exceptions: exceptions that are not runtime exceptions and are checked by the compiler Java has different types of exceptions, including I/O Exceptions, runtime exceptions and exceptions of your own creation, etc. Checked exceptions are exceptions that are not runtime exceptions. Exceptions of all Exception classes and subclasses other than Runtime Exception which is a subclass of Exception are checked by the compiler and will result in compiler errors if they are not either caught or specified

83 Some Terms in Exception Handling (3)
Exceptions That Can Be Thrown Within the Scope of the Method The throw statement includes more than just the exceptions that can be thrown directly by the method: This phrase includes any exception that can be thrown while the flow of control remains within the method. This statement includes both Exceptions that are thrown directly by the method with Java's throw statement. Exceptions that are thrown indirectly by the method through calls to other methods

84 import java.io.*; public class InputFile { private FileReader in; public InputFile(String filename) in = new FileReader(filename); } public String getWord() int c; StringBuffer buf = new StringBuffer(); do c = in.read(); if (Character.isWhitespace((char)c)) return buf.toString(); else buf.append((char)c); } while (c != -1); Compiler give error message about the bold line. - The FileReader read method throws a java.io.IOException if for some reason it can't read from the file

85 import java.io.*; public class InputFileDeclared { private FileReader in; public InputFileDeclared(String filename) throws FileNotFoundException in = new FileReader(filename); } public String getWord() throws IOException { int c; StringBuffer buf = new StringBuffer(); do c = in.read(); if (Character.isWhitespace((char)c)) return buf.toString(); else buf.append((char)c); } while (c != -1);

86 The try Block (1) The first step in writing any exception handler is putting the Java statements within which an exception can occur into a try block. The try block is said to govern the statements enclosed within it and defines the scope of any exception handlers (established by subsequent catch blocks) associated with it. Syntax: try { //java statements }

87 The try Block (2) Put statements in try block
Put each statement that might throw exceptions within its own try block and provide separate exception handlers for each try block Some statements, particularly those that invoke other methods, could potentially throw many types of exceptions. A try block consisting of a single statement might require many different exception handlers. Put all of the statements that might throw exceptions within a single try block and associate multiple exception handlers with it.

88 The try Block (3) Exception handlers must be placed immediately following their associated try block. If an exception occurs within the try block, that exception is handled by the appropriate exception handler associated with the try block.

89 The catch Block(s) (1) Associate exception handlers with a try block by providing one or more catch blocks directly after the try block The catch block contains a series of legal Java statements. These statements are executed if and when the exception handler is invoked. Syntax: catch (AThrowableObjectType variableName) { //Java statements }

90 The catch Block(s) (2) The runtime system invokes the exception handler when the handler is the first one in the call stack whose type matches that of the exception thrown The order of your exception handlers is important, particularly if you have some handlers which are further up the exception hierarchy tree than others Those handlers designed to handle exceptions furthermost from the root of the hierarchy tree should be placed first in the list of exception handlers Otherwise, those handler designed to handle a specialized "leaf" object may be preempted by another handler whose exception object type is closer to the root if the second exception handler appears earlier in the list of exception handlers

91 Argument of the catch Block(s)
The argument type declares the type of exception object that a particular exception handler can handle and must be the name of a class that inherits from the Throwable class. As in a method declaration, there is a parameter which is the name by which the handler can refer to the exception object. You access the instance variables and methods of exception objects the same way that you access the instance variables and methods of other objects

92 Catching Multiple Exception Types with One Handler
Java allows to write general exception handlers that handle multiple types of exceptions Exception handler can be written to handle any class that inherits from Throwable. If you write a handler for a "leaf" class (a class with no subclasses), you've written a specialized handler: it will only handle exceptions of that specific type. If you write a handler for a "node" class (a class with subclasses), you've written a general handler: it will handle any exception whose type is the node class or any of its subclasses

93 Catch These Exceptions
To catch only those that are instances of a leaf class. An exception handler that handles only invalid index exceptions : catch (InvalidIndexException e) { } A method can catch an exception based on its group or general type by specifying any of the exception's superclasses in the catch statement. To catch all array exceptions regardless of their specific type, an exception handler: catch (ArrayException e) { } This handler would catch all array exceptions including InvalidIndexException, ElementTypeException, and NoSuchElementException. Set up an exception handler that handles any Exception : catch (Exception e) { }

94 The finally Block finally block provides a mechanism that allows your method to clean up after itself regardless of what happens within the try block. The final step in setting up an exception handler is providing a mechanism for cleaning up the state of the method before allowing control to be passed to a different part of the program. Do this by enclosing the cleanup code within a finally block. The runtime system always executes the statements within the finally block regardless of what happens within the try block.

95 Specifying (Declaring) the Exceptions Thrown by a Method
Sometimes it is best to handle exceptions in the method where they are detected, and sometimes it is better to pass them up the call stack and let another method handle them. In order to pass exceptions up the call stack, you must specify or declare them To specify that a method throws exceptions, add a throws clause to the method signature for the method.

96 throws InterruptedException, MyException, HerException, UrException
void myMethod() throws InterruptedException, MyException, HerException, UrException { //method code }//end myMethod() Any method calling this method would be required to either handle these exception types, or continue passing them up the call stack. Eventually, some method must handle them or the program won't compile.

97 The throw Statement Before you can catch an exception, some Java code somewhere must throw one. Any Java code can throw an exception: your code, code from a package written by someone else or the Java runtime system. Exceptions are always thrown with the Java throw statement The object be thrown may be an instance of any subclass of the Throwable class Syntax: throw myThrowableObject;

98 Use Exception Classes Use a class written by someone else. For example, the Java development environment provides a lot of exception classes that you could use. Write an exception class of your own It is possible to define your own exception classes, and to cause objects of those classes to be thrown whenever an exception occurs according to your definition of an exception.


Download ppt "G. Pullaiah College of Engineering and Technology"

Similar presentations


Ads by Google