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.
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.
|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||–|
|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(“I think I can…”);
FileReader reader =newFileReader(“myfile.txt”);
System.out.println(“I knew I could!”);
System.out.println(“File not found.”);
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
I think I can…
I knew I could!
If the file does not exist, however, the try block halts at the FileReader constructor, and the catch block is run:
I think I can…
File not found.