Write a Java program that shows the usage of try, catch, throw, throws and finally.

//stack.java

 class Stack

{

private int[] a;

private int size;

private int top;


public Stack(int size)

{

this.size = size;

a = new int[size];

top = -1;

}


public void push(int item) throws StackFull

{

if(top == size-1)

{

throw new StackFull("stack is full item cannot be stored");

}

{

top = top + 1;

a[top] = item;

}

}


int pop() throws StackEmpty

{

if(top == -1)

{

throw new StackEmpty("stack is empty");

}

{

int item = a[top];

top = top - 1;

return item;

}

}

}

//StackDemo.java

class StackDemo

{

public static void main(String[] args)

{

try

{

Stack s = new Stack(4);

s.push(10);

s.push(20);

s.push(30);

s.push(40);

s.push(50);

s.pop();

}

catch(StackFull e)

{

System.out.println(e);

}

catch(StackEmpty e)

{

System.out.println(e);

}

}

}



//StackEmpty.java

class StackEmpty extends Exception

{

public StackEmpty(String s)

{

super(s);

}

}


//Stackfull.java

class StackFull extends Exception

{

public StackFull(String s)

{

super(s);

}

}




Comments

Popular posts from this blog

MatrixMultiplication

FrequencyCountDemo