The Fundamentals

The Fundamentals

An exceptional condition is a problem that prevents the continuation of the current method or scope. It’s important to distinguish an exceptional condition from a normal problem, in which you have enough information in the current context to somehow cope with the difficulty. With an exceptional condition, you cannot continue processing because you don’t have the information necessary to deal with the problem in the current context. All you can do is jump out of the current context and relegate that problem to a higher context. This is what happens when you throw an exception.

Errors that result from program activity are represented by subclasses of Exception. For example, divide-by-zero, array boundary, and file errors fall into this category. In general, your program should handle exceptions of these types. An important subclass of Exception is RuntimeException, which is used to represent various common types of run-time errors.
This is the general form of an exception-handling block:

		try {
			// code to monitor for exception
		} catch (Exception e) { // Exception type returned, handling object may
			// be anything, object defined to handle exception
			// code to handle exception here
		} finally {
			// block of code to be executed after try block ends
		}

A Simple Exception Example

public class ExceptionBasics {
	public static void main(String args[]) {
		int nums[] = new int[4];
		try {
			System.out.println("Before exception is generated.");
			// Generate an index out-of-bounds exception.
			nums[10] = 10; // array only generated for 4 elements and we are
							// accessing 10th element
			System.out.println("this won't be displayed");
		} catch (ArrayIndexOutOfBoundsException exc) {
			// catch the exception
			System.out.println("Index out-of-bounds!");
		}
		System.out.println("After catch statement.");
	}
}