如何实现自定义异常



这是我的加班,如果销售目标未达到,则打印消息除外。

public class OverTimeException extends Exception {
        int salesTarget;
        public OverTimeException(int s) {
            salesTarget = s;
        }
        String myPrint()
        {
            return "exception caught because sales target is " + salesTarget; 

        }
    }

这是我想在 salesTarget 方法中使用异常的 Clerk 类。我的问题是如何将异常实现到 salesTarget 方法中?谢谢

public class Clerk extends Admin implements ClerkInterface {
    final double payRate = 13.00;
    final int salesTargetNum = 46;

    //Member variables
    private double unitSold;
    //Constructor
    public Clerk(String inName, String inId, double inHoursWorked,
            double intkPay, double inAdmin_quota,double inUnitSold) {
        super(inName, inId, inHoursWorked, intkPay, inAdmin_quota);
        setUnitSold(inUnitSold);
    }

    //setUnitsSold method
    private void setUnitSold(double inUnitSold) {
        unitSold = inUnitSold;
    }

    //getUnitsSold
    public double getUnitsSold(){
        return unitSold;
    }


    //toString method
    public String toString()
    {
        return " " + super.toString() + "Admin Quota " + getAdmin_quota() + "Units Sold" + getUnitsSold();

    }

    //method to confirm sales targets are made from ClerkInterface.
    public void salesTarget() {
        if(salesTargetNum >= unitSold){
            System.out.println("Clerk has not meet sales target");
        }
        else
        {
            System.out.println("Clerk has meet sales target");
        }
    }


    }//end Clerk

你想抛出异常的地方,只需执行

throw new OverTimeException(salesTargetNum);

我强烈建议您重写 Exception 类中的所有构造函数。

import java.lang.Exception;
import java.lang.String;
import java.lang.Throwable;
public class OvertimeException extends Exception {
    /**
     * Constructs a new exception with <code>null</code> as its detail message.
     * The cause is not initialized, and may subsequently be initialized by a
     * call to {@link #initCause}.
     */
    public OvertimeException() {
        super();    //To change body of overridden methods use File | Settings | File Templates.
    }
    /**
     * Constructs a new exception with the specified cause and a detail
     * message of <tt>(cause==null ? null : cause.toString())</tt> (which
     * typically contains the class and detail message of <tt>cause</tt>).
     * This constructor is useful for exceptions that are little more than
     * wrappers for other throwables (for example, {@link
     * java.security.PrivilegedActionException}).
     * @param cause the cause (which is saved for later retrieval by the
     *              {@link #getCause()} method).  (A <tt>null</tt> value is
     *              permitted, and indicates that the cause is nonexistent or
     *              unknown.)
     * @since 1.4
     */
    public OvertimeException(Throwable cause) {
        super(cause);    //To change body of overridden methods use File | Settings | File Templates.
    }
    /**
     * Constructs a new exception with the specified detail message.  The
     * cause is not initialized, and may subsequently be initialized by
     * a call to {@link #initCause}.
     * @param message the detail message. The detail message is saved for
     *                later retrieval by the {@link #getMessage()} method.
     */
    public OvertimeException(String message) {
        super(message);    //To change body of overridden methods use File | Settings | File Templates.
    }
    /**
     * Constructs a new exception with the specified detail message and
     * cause.  <p>Note that the detail message associated with
     * <code>cause</code> is <i>not</i> automatically incorporated in
     * this exception's detail message.
     * @param message the detail message (which is saved for later retrieval
     *                by the {@link #getMessage()} method).
     * @param cause   the cause (which is saved for later retrieval by the
     *                {@link #getCause()} method).  (A <tt>null</tt> value is
     *                permitted, and indicates that the cause is nonexistent or
     *                unknown.)
     * @since 1.4
     */
    public OvertimeException(String message, Throwable cause) {
        super(message, cause);    //To change body of overridden methods use File | Settings | File Templates.
    }
}
if(salesTargetNum >= unitSold){
    throw new OverTimeException(salesTarget);         
} else {
    System.out.println("Clerk has meet sales target");
}

请注意,在 OverTimeException 类中需要一个 toString 方法,而不是toPrint方法。

public class OverTimeException extends Exception {
    int salesTarget;
    public OverTimeException(int s) {
        salesTarget = s;
    } 
    public String toString() {  // Should be `toString`
        return "exception caught because sales target is " + salesTarget; 
    }
}

此外,将此例外添加到method declarationthrows 子句中。

你需要

  1. 在方法签名中声明异常
  2. 在需要时抛出该方法

例如

public void salesTarget() throws OvertimeException{
   ...
   throws new OvertimeException(s);
}

请注意,无需在方法签名中声明未经检查的异常。

使用

 public void salesTarget() throws OverTimeException {
    if(salesTargetNum >= unitSold){
        throw new OverTimeException(salesTargetNum);
    } else {
        System.out.println("Clerk has meet sales target");
    }
}

您的异常应该像这样声明。

public class OverTimeException extends Exception {
    public OvertimeException(int s){
        super("exception caught because sales target is " + s);
    }
}

最新更新