Linked list implementation with exceptions.
Node has not changed

public class Node {
    private int data;
    private Node next;

    public Node(int d) {
	data = d;
	next = null; // can skip this line: null is the default value
    }

    public int getData() {
	return data;
    }

    // return the next node
    public Node getNext() {
	return next;
    }

    // set the node 
    public void setNext(Node n) {
	next = n;
    }
}

addFront and removeFront throw exceptions when error condition happens.

public class LinkedList {
    private Node first;

    public LinkedList() {
	first = null;
    }

    // returns 'true' for an empty list and 'false' otherwise
    public boolean isEmpty() {
	return (first == null);
    }

    // returns the reference to the first node in the list
    // if the list is empty, null is returned.
    public Node getFirst() {
	return first;
    }

    // the method adds the node to the front of the list.
    // the 'next' field of the node is replaced by the reference to 
    // the rest of the list
    // If the parameter is null, an error message is printed and
    // the program stops
    public void addFront(Node n) throws Exception {
	// before calling a method on n, need to make sure 
	// that n is not null
	if (n == null) {
	
	    throw new Exception("Cannot add a null element to the list");
	   
	}
	// if we got here, n is not null
	n.setNext(first); 
	first = n;
    }

    // the method removes the first node from the list. 
    // if the list is empty, an error message is printed and
    // the program stops
    public void removeFront() throws Exception {
	// before removing an element from a list, need to make sure that
	// the list is not empty
	if (first == null) {
	
	    throw new Exception("Cannot remove an element from an empty list");
	    
	}
	// if we got here, the list is not empty
	first = first.getNext();
    }
}

The testing program catches the exception and continues

public class TestLinkedLists {
    public static void main(String [] args) {
	// testing nodes:
	Node first = new Node(5);
	Node second = new Node(6);

	LinkedList list = new LinkedList();
	
	// add the two nodes to the list
	try {
	    list.addFront(first);
	    list.addFront(second);
	    list.addFront(null);
	} catch (Exception e) {
	    System.out.println(e);
	    System.out.println("continue after the exception");
	}

	System.out.println("print the list");
	Node n = list.getFirst();
	while (n != null) {
	    System.out.println(n.getData());
	    n = n.getNext();
	}
    }
}

This is an example from CSci 2101 course.

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.