Thursday, September 15, 2011

Unchecked Exception

An example that shows how/where an un-checked exception can be thrown. IllegalArgumentException is a sub-class of RuntimeException.

browse

package org.megha.blog.example.part8;

public class MyMath {

	/**
	 * Calculates the average of the numbers provided.
	 *
	 * @param numbers the numbers to average over.
	 * @throws IllegalArgumentException if no numbers a specified
	 */
	public static double average(int... numbers) {
		// note the use of var-args above. java collapses all the arguments into an array
		if (numbers.length == 0) {
			throw new IllegalArgumentException("no numbers to average over!");
		}
		int sum = 0;
		for(int i : numbers) {
			sum = sum + i;
		}
		return ((double) sum) / numbers.length;
	}

	public static void main(String args[]) {

		// averaging works over any number of arguments
		System.out.println(MyMath.average(1, 2, 3, 7, 9, 10));
		System.out.println(MyMath.average(55, 77));
		System.out.println(MyMath.average(3));

		// but when it's called with no arguments, an unchecked exception is thrown.
		// ofcourse, we know about it already, so we have a try/catch block in place.
		// unchecked/runtime exceptions usually happen when some assumed condition, or
		// an api contract is not met by the programmer. eg passing in a null, where
		// null is not expected, or trying to lookup into an array beyond it's bounds.
		try {
			System.out.println(MyMath.average());
		} catch (IllegalArgumentException e) {
			System.out.println("Exception caught: " + e);
		}
		System.out.println("still running... :)");
	}
}

No comments:

Post a Comment