Do I need new exceptions for every invalid field

Question from huh#0893

are exception classes used per class field or can one exception class handle every field?

If my class has fields for

String name, int ID, double salary, double hours

If I need exceptions for handling empty name "", negative number ID, negative salary, negative hours, do I need a new exception class for every field?

by exception class I mean something like this

public class InvalidPayRate extends Exception
{
    public InvalidPayRate(double p)
    {
        super("Hourly pay rate may not be negative or greater than 25: " + p);
    }
}

The reason you don't want a specific InvalidPayRate exception in this case is that it is an unrecoverable scenario.

An Invalid pay rate will almost always mean programmer error.

public class InvalidPayRate extends Exception
{
    public InvalidPayRate(double p)
    {
        super("Hourly pay rate may nor be negative or greater than 25: " + p);
    }
}

if you were to throw this exception from somewhere you would need to declare that you throw it and then the caller would need to handle it.

So at the very least you want this to extend RuntimeException.

public class InvalidPayRate extends RuntimeException
{
    public InvalidPayRate(double p)
    {
        super("Hourly pay rate may nor be negative or greater than 25: " + p);
    }
}

Since it's a programmer error you don't expect to catch.

At that point you need to weigh the value of doing this for each field in a class and the value is just having the stack trace say "InvalidPayRate", which you can already put into the message.


<- Index