关于java中自定义异常的小总结

简单的try catch很简单,但是对于自定义的Exception很多初学者都感到有些头痛,我小总结了下

简单的声明与使用,比如说我们的文件是TestException.java

public class TestException{
	public static void main(String[] args){
		try{
			new abc().abcd();
		}catch(Myexception a){
			System.out.println(a.getMessage());
		}finally{
		....
		}
	}
} //这里是public class的结尾

class Myexception extends Exception{
	myexception(String msg) { //构造方法
		super(msg)	 		//调用基类的构造方法,将msg信息传递给基类
	}						//还可以定义其它的构造方法,具体查API文档
}

class abc{
	int a,b;
	public void abcd() throws Myexception{
		if(...){
			throw new Myexception("msg") ;//这时抛出一个新的异常,用getMessage()方法可以得到这个信息-----“msg”;
		}
	}
}
举一个完整的实例

public class Myexception{
	public static void main(String[] args){
	  try{
		new chufa().chu(10,0);
	  }catch(chulingException a){
	  	System.out.println(a.getMessage());
	  }catch(chufuException b){
	  	System.out.println(b.getMessage());
	  }finally{
	  System.out.println("怎么都打印!!!");
	  }
	}
}


	class chulingException extends Exception{
		chulingException(String msg){
			super(msg);
		}
	}
	
	class chufuException extends Exception{
		chufuException(String msg){
			super(msg);
		}
	}
	
	class chufa{
		int x,y;
		public void chu(int m, int n) throws chulingException,chufuException{
			x = m;
			y = n;
			if(y<0){
				throw new chufuException("除数不能为负数");
			}else if(y==0){
				throw new chulingException("除数不能为0");
			}else{
			 System.out.println(x/y);
			}
		}
	}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值