throw与throws与自定义异常

class Math{
	public int div(int i,int j) throws Exception{	// 定义除法操作,如果有异常,则交给被调用处处理
		int temp = i / j ;	// 计算,但是此处有可能出现异常
		return temp ;
	}
};
public class ThrowsDemo01{
	public static void main(String args[]){
		Math m = new Math() ;		// 实例化Math类对象
		try{
			System.out.println("除法操作:" + m.div(10,2)) ;
		}catch(Exception e){
			e.printStackTrace() ;	// 打印异常
		}
	}
};

class Math{
	public int div(int i,int j) throws Exception{	// 定义除法操作,如果有异常,则交给被调用处处理
		int temp = i / j ;	// 计算,但是此处有可能出现异常
		return temp ;
	}
};
public class ThrowsDemo02{
	// 在主方法中的所有异常都可以不使用try...catch进行处理
	public static void main(String args[]) throws Exception{
		Math m = new Math() ;		// 实例化Math类对象
		System.out.println("除法操作:" + m.div(10,0)) ;
	}
};

使用throws声明的方法表示此方法不处理异常,而交给方法的调用处处理异常;与throws不同的是,throw抛出一个异常,抛出时直接抛出异常类的实例化对象即可

public class <span style="font-family: Arial, Helvetica, sans-serif;">ThrowDemo01</span>{	
	public static void main(String args[]){
		try{
			throw new MyException("自己抛出异常。") ;	 // 抛出异常的实例化对象
		}catch(Exception e){     <span style="font-family: Arial, Helvetica, sans-serif;">									</span><span style="font-family: Arial, Helvetica, sans-serif;">// 捕获异常</span>
		System.out.println(e) ;
		}
	}
}

class Math{
	public int div(int i,int j) throws Exception{	// 定义除法操作,如果有异常,则交给被调用处处理
		System.out.println("***** 计算开始 *****") ;
		int temp = 0 ;	// 定义局部变量
		try{
			temp = i / j ;	// 计算,但是此处有可能出现异常
		}catch(Exception e){       
			throw e ;         //把异常交给调用处
		}finally{	// 不管是否有异常,都要执行统一出口
			System.out.println("***** 计算结束 *****") ;
		}
		return temp ;
	}
};
public class ThrowDemo02{
	public static void main(String args[]){
		Math m = new Math() ;
		try{
			System.out.println("除法操作:" + m.div(10,0)) ;
		}catch(Exception e){
			System.out.println("异常产生:" + e) ;
		}
	}
};

class MyException extends Exception{	// 自定义异常类,继承Exception类
	public MyException(String msg){
		super(msg) ;	// 调用Exception类中有一个参数的构造方法,传递错误信息
	}
};
public class DefaultException{	
	public static void main(String args[]){
		try{
			throw new MyException("自定义异常。") ;	 // 抛出异常
		}catch(Exception e){
			System.out.println(e) ;
		}
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值