自定义异常详解

在 Java 中你可以自定义异常。编写自己的异常类时需要记住下面的几点。

  • 所有异常都必须是 Throwable 的子类。
  • 如果希望写一个检查性异常类,则需要继承 Exception 类。
  • 如果你想写一个运行时异常类,那么需要继承 RuntimeException 类。

可以像下面这样定义自己的异常类:

class MyException extends Exception{ }
举例说明:
// 自定义异常类
public class TestException extends Exception{
private static final long serialVersionUID = 1L; public TestException() { super(); } public TestException(String msg) { super(msg); } }
// 使用自定义异常抛出异常信息
public class Demo {
 public static void main(String[] args){   int a = 12;   int b = -2;   try {    if(b < 0){     throw new TestException("除数为负数");    }else{     System.out.println("result = "+a/b);    }   } catch (TestException e) {    e.printStackTrace();   }  } }

示例2:
public class TestException extends Exception{

	private static final long serialVersionUID = 1L;
	
	private int value;

	public TestException() {
		super();
	}
	
	public TestException(String msg) {
		super(msg);
	}

	public TestException(String msg,int value){
		super(msg);
		this.value = value;
	}

	public int getValue() {
		return value;
	}	
}

public class Test { public int div(int a,int b) throws TestException{ if(b < 0){ throw new TestException("除数为负:",b);// 手动抛出一个自定义异常对象 } return a/b; } }

// 调用测试

public class Demo {
	public static void main(String[] args){
		Test t = new Test();
		try {
			int result = t.div(12, 2);
			System.out.println("result = "+result);
		} catch (TestException e) {
			System.out.println(e.toString());
			System.out.println("负数是:"+e.getValue());
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值