Java Try, Catch, Finally

I love Unix first. Next Java for its simplicity and its nomenclature.
In Unix, Thread, Parent Thread, Orphan Thread / Daemon Thread, Kill, ….all taken from day to day life…

These are the common words we use in our day to day life…Try, Catch, Finally….
Now apply these things to life…we are more safe….
This is called improving life by programming…. : )

/**
 * Try, Catch and Finally blocks can't exist on their own. Only permitted
 * combinations are
 * <p>
 * try-catch
 * <p>
 * try-catch-finally
 * <p>
 * try-finally
 * <p>
 * 
 * @author Bhavani P Polimetla
 * 
 * @since April-27-2012
 */
public class TryTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		System.out.println("============= Test 1 =============");
		try {
			System.out.println("From function==>" + devide(10, 2));
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		System.out.println("============= Test 2 =============");
		try {
			Thread.sleep(5000);
			System.out.println("From function==>" + devide(10, 0));
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		System.out.println("============= Test 3 =============");
		try {
			Thread.sleep(5000);
			System.out.println("From function==>" + devide2(10, 2));
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		System.out.println("============= Test 4 =============");
		try {
			Thread.sleep(5000);
			System.out.println("From function==>" + devide2(10, 0));
		} catch (Exception ex) {
			ex.printStackTrace();
		}

	}

	public static long devide(int x, int y) {
		long result = 0;

		try {
			result = x / y;
			return result;
		} catch (NullPointerException ex) {
			ex.printStackTrace();

		} finally {
			System.out.println("==== I am in finally1 ====");
		}

		return result;
	}

	public static long devide2(int x, int y) {
		long result = 0;

		try {
			result = x / y;
			return result;
		} finally {
			System.out.println("==== I am in finally2 ====");
		}

		// Unreachable code
		// return result;
	}

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s