Exception Throwing Principles

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 :-

  1. 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.
  2. 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.
  3. The java.lang package defines several classes and exceptions. Some of these classes are not checked while some other classes are checked.
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
  1. 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!”);



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:

Ready? Go!

I think I can…

File not found.

All done.

Defensive Programming

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.

Error Handling

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:

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.