自定义异常有两种,分别是继承Exception和Throwable 类,因为Throwable是exception的父类,所以,继承Exception和继承Throwable效果差不多,下面是继承Exception的自定义的类的实现和用法。package com.cvicse.exception;
1、自定义异常
/**
*
* @功能自定义异常 ObjAlreadyExistException
* @author 创建人 gao_jie
* @date 创建日期 Jul 3, 2008
* @version 1.0
*
*/
public class ObjAlreadyExistException extends Exception {
private static final long serialVersionUID = 1L;
/**
* 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 ObjAlreadyExistException() {
super();
}
/**
* @param message
* the detail message. The detail message is saved for later
* retrieval by the {@link #getMessage()} method.
*/
public ObjAlreadyExistException(String message) {
super(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 ObjAlreadyExistException(String message, Throwable cause) {
super(message, cause);
}
/**
* @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 ObjAlreadyExistException(Throwable cause) {
super(cause);
}
}
2、在函数中应用自己的异常
package com.cvicse.service;
import com.cvicse.exception.ObjAlreadyExistException;
/**
*
*@功能;定义一个实现类,它应用了自定义的异常
*@author创建人gao_jie
*@date创建日期Jul3,2008
*@version1.0
*
*/
publicclass CaculateFunction {
/**
*计算函数中的加函数
*@parama
*@paramb
*@throwsObjAlreadyExistException
*/
publicvoid add(float a, float b) throws ObjAlreadyExistException {
if (a == b)
thrownew ObjAlreadyExistException("输入的数相等!");
}
}
3、在主函数中调用该函数
package com.cvicse.mian;
import com.cvicse.exception.ObjAlreadyExistException;
import com.cvicse.service.CaculateFunction;
/**
*
*@功能
*@author创建人gao_jie
*@date创建日期Jul3,2008
*@version1.0
*
*/
publicclass Application {
privatestatic CaculateFunction CaculateFunction = null;
/**
*@paramargs
*/
publicstaticvoid main(String[] args) {
// TODO Auto-generated method stub
CaculateFunction = new CaculateFunction();
try {
CaculateFunction.add(12, 12);
} catch (ObjAlreadyExistException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}