基本原则
自定义异常类通常需要编写几个重载的构造器。
自定义的异常通过
throw
抛出。
自定义异常最重要的是异常类的名字,当异常出现时,可以根据名字判断异常类型。
简单的代码案例
继承了Exception的自定义异常处理类MyException
class MyException extends Exception {
//异常信息
private String message;
public MyException(String message) {
super(message);
this.message = message;
}
}
调用自定义的异常处理类
public class UseMyException{
public void regist(int num) throws MyException {
if (num < 0)
throw new MyException("输入参数有误,不能为负值");
else
System.out.println(num);
}
}
try-catch自定义的异常处理类
public class UseMyExceptionTest {
@Test
public void test(){
try{
UseMyException useMyException=new UseMyException();
useMyException.regist(-1);
}catch (MyException me){
System.out.println("MyException:"+me.getMessage());
}
}
}
测试结果
包含更多现场信息的异常类定义
class UseMyException{
public void regist(int num) throws MyException {
if (num < 0)
throw new MyException("输入参数有误,不能为负值",1);
else
System.out.println(num);
}
public void regist2(int id) throws AdditionalInformationException {
if (id < 0)
throw new AdditionalInformationException("输入参数有误,不能为负值",id);
else
System.out.println(id);
}
}
class AdditionalInformationException extends Exception {
private int amount;
public AdditionalInformationException(String message,int amount) {
super(message);
this.amount = amount;
}
public double getAmount(){
return amount;
}
}
class AdditionalInformationExceptionTest {
public static void main(String[] args) {
try{
UseMyException useMyException=new UseMyException();
useMyException.regist2(-1);
}catch (AdditionalInformationException me){
System.out.println("AdditionalInformationException:"
+me.getMessage()+" 错误的参数值为:"
+me.getAmount());
}
}
}
测试结果
版权声明:本文为twi_twi原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。