RMI and exceptions

Malachi picture Malachi · Mar 4, 2009 · Viewed 12.4k times · Source

I am new to using RMI and I am relatively new to using exceptions.

I want to be able to throw an exception over RMI (is this possible?)

I have a simple server which serves up students and I have delete method which if the student doesn't exist I want to throw a custom exception of StudentNotFoundException which extends RemoteException (is this a good thing to do?)

Any advice or guidance would be greatly appreciated.

Server Interface method

    /**
 * Delete a student on the server
 * 
 * @param id of the student
 * @throws RemoteException
 * @throws StudentNotFoundException when a student is not found in the system
 */
void removeStudent(int id) throws RemoteException, StudentNotFoundException;

Server method implementation

    @Override
public void removeStudent(int id) throws RemoteException, StudentNotFoundException
{
    Student student = studentList.remove(id);

    if (student == null)
    {
        throw new StudentNotFoundException("Student with id:" + id + " not found in the system");
    }
}

Client method

    private void removeStudent(int id) throws RemoteException
{
    try
    {
        server.removeStudent(id);
        System.out.println("Removed student with id: " + id);
    }
    catch (StudentNotFoundException e)
    {
        System.out.println(e.getMessage());
    }

}

StudentNotFoundException

package studentserver.common;

import java.rmi.RemoteException;

public class StudentNotFoundException extends RemoteException
{
    private static final long serialVersionUID = 1L;

    public StudentNotFoundException(String message)
    {
        super(message);
    }
}

Thank you for your reply I have now managed to fix my problem and realised that extending RemoteException was bad idea.

Answer

Outlaw Programmer picture Outlaw Programmer · Mar 4, 2009

It's OK to throw any kind of exception (even custom ones), just make sure to package them up in your export .jar file (if you're using a version of Java where you need to do this manually).

I wouldn't subclass RemoteException, though. Those are typically thrown if there is some kind of connection problem. Presumably, your client will handle connection problems differently from other types of problems. You might tell the user the server is down when you catch a RemoteException, or connect to a different server. For StudentNotFoundException, you probably want to give the user another chance at entering the student info.