Exception handling is the process of responding to the occurrence, during computation, of exceptions – anomalous or exceptional events requiring special processing – often changing the normal flow of program execution. It is provided by specialized programminglanguage constructs or computer hardware mechanisms.

In general, an exception is handled (resolved) by saving the current state of execution in a predefined place and switching the execution to a specific subroutine known as an exception handler. If exceptions are continuable, the handler may later resume the execution at the original location using the saved information. For example, a floating point divide by zero exception will typically, by default, allow the program to be resumed, while an out of memory condition might not be resolvable transparently.

Alternative approaches to exception handling in software are error checking, which maintains normal program flow with later explicit checks for contingencies reported using special return values or some auxiliary global variable such as C’s errno or floating point status flags; or input validation to preemptively filter exceptional cases.

Throwing an Exception:

Various exceptions are thrown at the bytecode or system level, such as when an integer division by zero is attempted, when an attempt is made to access an invalid array index, or when Java’s object allocator runs out of heap memory. However, a program can also deliberately throw an exception. Many exceptions that occur are deliberately thrown by Java library code or by user code when they detect a particular error condition.

To throw an exception, the throw keyword is used, followed by the exception object to be thrown. The most common case is to create the exception object on the fly, so that the code to throw an exception looks as follows:

throw new IOException(“Some required files are missing”);

We can create an instance of any public exception class from the libraries, or we can create our own exception subclass.

Exception Classes:

The hierarchy of exception classes commence from Throwable class which is the base class for an entire family of exception classes, declared in java.lang package as java.lang.Throwable. A throwable contains a snapshot of the execution stack at the time it was created and also a message string that gives more information about the error. This class can be instantiated and thrown by the program. The throwable class is further divided into two subclasses :-

Exceptions - Exceptions are thrown if any kind of unusual condition occurs that can be caught. Sometimes it also happens that the exception could not be caught and the program may get terminated. Remember that they are a member of Exception family and can be type ofChecked or Unchecked exception.

Errors - When any kind of serious problem occurs which could not be handled easily likeOutOfMemoryError then an error is thrown. Well, errors are not something which is thrown by you rather they are thrown by the Java API or by the Java virtual machine itself i.e. only the exceptions are thrown by your code and not the errors. Also Remember that they are a member of Error family.

The java.lang package defines several classes and exceptions. Some of these classes are not checked while some other classes are checked.

EXCEPTIONS

DESCRIPTION

CHECKED

UNCHECKED

ArithmeticException

Arithmetic errors such as a divide by zero

-

YES

ArrayIndexOutOfBoundsException

Arrays index is not within array.length

-

YES

ClassNotFoundException

Related Class not found

YES

-

IOException

InputOuput field not found

YES

-

IllegalArgumentException

Illegal argument when calling a method

-

YES

InterruptedException

One thread has been interrupted by another thread

YES

-

NoSuchMethodException

Nonexistent method

YES

-

NullPointerException

Invalid use of null reference

-

YES

NumberFormatException

Invalid string for conversion to number

-

YES

As you have come to know that exceptions are Objects that means an object is thrown when you throw an exception. Moreover only those objects could be thrown whose classes are derived from

Throwing and catching exceptions:

For throwing and catching exceptions in java, try and catch blocks are really simple. The basic syntax follows. For this example, we’ll try to read a file that doesn’t exist. (The details of file I/O comes later in this tutorial; the important part is just that this code is risky: if the file “myfile.txt” doesn’t exist, the FileReader constructor throws a FileNotFoundException.)

System.out.println(“Ready? Go!”);

try

{

System.out.println(“I think I can…”);

FileReader reader =newFileReader(“myfile.txt”);

System.out.println(“I knew I could!”);

}

catch(FileNotFoundException ex)

{

System.out.println(“File not found.”);

}

System.out.println(“All done.”);

Whenever a method of some class could throw an exception, you should use the try/catch block. The compiler tries to run the code in the try block. If any statement in the block throws an exception, the JVM jumps to the appropriate catch block; that is, the catch block that names the thrown exception. If no code in the try block throws an exception, the catch block is skipped.

Consider the code above. If the named file exists, the try block runs to completion, and the catch block is skipped. The output is

Ready? Go!

I think I can…

I knew I could!

All done.

If the file does not exist, however, the try block halts at the FileReader constructor, and the catch block is run:

Defensive programming is a form of defensive design intended to ensure the continuing function of a piece of software in spite of unforeseeable usage of said software. The idea can be viewed as reducing or eliminating the prospect of Murphy’s Law having effect. Defensive programming techniques are used especially when a piece of software could be misused mischievously or inadvertently to catastrophic effect.

Defensive programming is an approach to improve software and source code, in terms of:

General quality – Reducing the number of software bugs and problems.

Making the source code comprehensible – the source code should be readable and understandable so it is approved in a code audit.

Making the software behave in a predictable manner despite unexpected inputs or user actions.

In the progressive phase of developing a project, instead of designing and then building the completeapplication in one massive leap, prototyping can be used to examine parts of a system.A prototype is a version of the application where one part is simulated in order toexperiment with other parts. For example, one can implement a prototype to test agraphical user interface. In that case, the logic of the application may not be properlyimplemented. Instead, we would write simple implementations for those methods thatsimulate the task. For example, when calling a method to find a free seat in thecinema system, a method could always return seat 3, row 15, instead of actuallyimplementing the search. Prototyping allows us to develop an executable (but notfully functional) system quickly, so that we can investigate parts of the application inpractice.

Prototypes are also useful for single classes to aid a team development process. Often,when different team members work on different classes, not all classes take the sameamount of time to be completed. In some cases a missing class can hold upcontinuation of development and testing of other classes. In those cases it can bebeneficial to write a class prototype. The prototype has implementations of all methodstubs, but instead of containing full, final implementations, the prototype only simulates the functionality. Writing a prototype should be possible quickly, anddevelopment of client classes can then continue using the prototype until the class isimplemented.

Moving towards the documentation of a project or application, afterclassifying the classes and their interfaces, and before starting to implement themethods of a class, the interface should be documented. This includes writing a classcomment and method comments for every class in the project. These should be defined in adequate detail to identify the overall purpose of each class and method.

Along with analysis and design, documentation is a further area that is often neglected by beginners. It is not easy for inexperienced programmers to see whydocumentation is so important. The reason is that inexperienced programmers usuallywork on projects that have only a handful of classes, and that are written in the spanof a few weeks or months. A programmer can get away with bad documentation whenworking on these mini-projects.

However, even experienced programmers often wonder how it is possible to write thedocumentation before the implementation. This is because they fail to appreciate that good documentation focuses on high-level issues, such as what a class or method does, rather than low-level issues, such as exactly how it does it. This is usuallysymptomatic of viewing the implementation as being more important than the design.

When you define a new interface, you are defining a new reference data type. You can use interface names anywhere you can use any other data type name. If you define a reference variable whose type is an interface, any object you assign to it must be an instance of a class that implements the interface.

As an example, here is a method for finding the largest object in a pair of objects, for any objects that are instantiated from a class that implements Relatable:

public Object findLargest(Object object1, Object object2) {

Relatable obj1 = (Relatable)object1;

Relatable obj2 = (Relatable)object2;

if ((obj1).isLargerThan(obj2) > 0)

return object1;

else

return object2;

}

By casting object1 to a Relatable type, it can invoke the isLargerThan method.

If you make a point of implementing Relatable in a wide variety of classes, the objects instantiated from any of those classes can be compared with the findLargest()method—provided that both objects are of the same class. Similarly, they can all be compared with the following methods:

public Object findSmallest(Object object1, Object object2) {

Relatable obj1 = (Relatable)object1;

Relatable obj2 = (Relatable)object2;

if ((obj1).isLargerThan(obj2) < 0)

return object1;

else

return object2;

}

public boolean isEqual(Object object1, Object object2) {

Relatable obj1 = (Relatable)object1;

Relatable obj2 = (Relatable)object2;

if ( (obj1).isLargerThan(obj2) == 0)

return true;

else

return false;

}

These methods work for any “relatable” objects, no matter what their class inheritance is. When they implement Relatable, they can be of both their own class (or superclass) type and a Relatable type. This gives them some of the advantages of multiple inheritance, where they can have behavior from both a superclass and an interface.

An interface is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface.

An interface is not a class. Writing an interface is similar to writing a class, but they are two different concepts. A class describes the attributes and behaviors of an object. An interface contains behaviors that a class implements.

Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class.

Defining an interface is similar to creating a new class:

public interface OperateCar {

// constant declarations, if any

// method signatures

// An enum with values RIGHT, LEFT

int turn(Direction direction,

double radius,

double startSpeed,

double endSpeed);

int changeLanes(Direction direction,

double startSpeed,

double endSpeed);

int signalTurn(Direction direction,

boolean signalOn);

int getRadarFront(double distanceToCar,

double speedOfCar);

int getRadarRear(double distanceToCar,

double speedOfCar);

……

// more method signatures

}

Note that the method signatures have no braces and are terminated with a semicolon.

In above example of interface in Java, SessionIDCreator is an interface while SerialSessionIDCreator is a implementation of interface.

Multiple inheritance of interfaces:

Multiple inheritance is a feature of some object oriented computer programming languages in which a class can inherit characteristics and features from more than one superclass. It is distinct to single inheritance where a class may only inherit from one particular superclass.

An abstract class can have abstract methods. You declare a method abstract by adding the abstract keyword in front of the method declaration. Here is how that looks:

public abstract class MyAbstractClass {

public abstract void abstractMethod();

}

An abstract method has no implementation. It just has a method signature.

If a class has an abstract method, the whole class must be declared abstract. Not all methods have to be abstract, even if the class is abstract. An abstract class can have a mixture of abstract and non-abstract classes.

Subclasses of an abstract class must implement (override) all abstract methods of its abstract superclass. The non-abstract methods of the superclass are just inherited as they are. They can also be overridden, if needed.

Here is an example subclass of MyAbstractClass:

public class MySubClass extends MyAbstractClass {

public void abstractMethod() {

System.out.println(“My method implementation”);

}

}

Notice how MySubClass has to implement the abstract method abstractMethod() from its superclass MyAbstractClass.

The only time a subclass of an abstract class is not forced to implement all abstract methods of its superclass, is if the subclass is also an abstract class.

Multiple inheritance is a feature of some object oriented computer programming languages in which a class can inherit characteristics and features from more than one superclass. It is distinct to single inheritance where a class may only inherit from one particular superclass.

Support we have four java class A, B, C, D

We start with simple example

1. Java Simple Inheritance Example

Class A

public class A {

public void a(){

System.out.println(“class A”);

}

}

Class B

public class B extends A{

public void a(){

System.out.println(“class B”);

}

}

Class C

public class C extends B{

public void a(){

System.out.println(“class C”);

}

}

Class D

public class D {

public static void main(String[] args) {

A a=new A();

A b=new B();

A c=new C();

a.a();

b.a();

c.a();

}

}

Output

class A
class B
class C

Flexibility through abstraction:

Abstraction in Java is achieved using interfaces and abstract class. abstract means something which is not complete or concrete but abstraction itself is a great programming concept and allow you to write code which is more flexible to change.

All Java errors are handled as exceptions. Exceptions extend the base class, Exception. You might have seen the try and catch block used. This is a way to “catch” exceptions – this essentially allowing you to handle various unexpected errors gracefully.

Life isn’t perfect. Much as we’d like to think otherwise, sometimes we encounter exceptional behavior. Things like missing files, badly formatted data to be parsed, and operations on null things are just a few of the many exceptions you may meet in your programming career. When these things happen, the JVM throws a temper tantrum, or (more technically) throws an exception.

How do you know if an exception could be thrown? The hard way is when the compiler complains that you didn’t properly handle the method. The easy way involves the API documentation. The standard API documentation on the Java site begins a method’s documentation with its header: the access level, return type, method name, parameters, miscellaneous modifiers, and the declared exceptions. For example, the readLine method in class java.io.BufferedReader throws IOException. Its header looks like this:

publicStringreadLine()throwsIOException
If a method might throw an exception, it has to declare that exception in its header using the throws statement. (Note: just because a method declares an exception doesn’t mean that it willthrow it, just that it might.) If you use a risky method, you have to tell the compiler what to do in case something bad happens. This is called catching the exception.

The preliminary design of a project is considered as one of the most significant parts of the project. You should adopt a strategy for planning tospend at least as much time working on the design as you plan to spend on theimplementation. Design of an application is not something that approaches before theprogramming – it is (the most significantchunk of) programming. Mistakes that arise in the code itself can later be fixed easily. Mistakes in the overalldesign can be, at best, expensive to put right and, at worst, fatal to the wholeapplication. In unlucky cases, they can be almost unfixable (short of starting all overagain).

User interface design:

As it matters with a well-designed application, this is pretty independent of the underlying logic of theapplication, so this can be done independently of designing the class structure for the rest of the project. BlueJ gives us the means of interacting with our application before a final user interface is available, so we can choose towork on the internal structure first.The user interface may be a GUI (graphical user interface) with menus and buttons, itcan be text based, or we can decide to run the application using the BlueJ method callmechanism.