Java关键字——throws和throw

throws关键字

  在定义一个方法时,可以使用throws关键字声明,使用throws声明的方法表示此方法不处理异常,而交给方法的调用处进行处理。

  使用了throws关键字,表示不管是否会有异常,在调用此方法处都必须进行异常处理

//=================================================
// File Name       :	throws_demo
//------------------------------------------------------------------------------
// Author          :	Common


// 类名:Math
// 属性:
// 方法:
class Math{
	public int div(int i,int j) throws Exception{	//本方法中可以不处理异常
		int temp = i/j;													//此处有可能产生异常
		return temp;														//返回计算结果
	}
}

//主类
//Function        : 	throws_demo
public class throws_demo {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		Math m =new Math();										//实例化Math对象
		try{																		//因为由throws,不管是否由异常,都必须处理
			System.out.println("除法操作="+m.div(1, 0));
		} catch (Exception e){
			e.printStackTrace();										//打印异常
		}
		
		
	}

}

与throws不同的是,可以直接使用throw抛出一个异常,抛出时直接抛出异常类的实例化对象即可

//=================================================
// File Name       :	throws_demo
//------------------------------------------------------------------------------
// Author          :	Common


// 类名:Math
// 属性:
// 方法:
class Math{
	public int div(int i,int j) throws Exception{	//本方法中可以不处理异常
		int temp = i/j;													//此处有可能产生异常
		return temp;														//返回计算结果
	}
}

//主类
//Function        : 	throws_demo
public class throws_demo {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		Math m =new Math();										//实例化Math对象
		try{																		//因为由throws,不管是否由异常,都必须处理
			System.out.println("除法操作="+m.div(1, 1));
			throw new Exception("自己抛出的异常");
		} catch (Exception e){
			e.printStackTrace();										//打印异常
		}
		
		
	}

}

throw和throws的应用

//=================================================
// File Name       :	throw_demo
//------------------------------------------------------------------------------
// Author          :	Common


// 类名:math
// 属性:
// 方法:
class math{
	public int div(int i,int j) throws Exception{	//本方法中可以不处理异常
		System.out.println("******计算开始******");
		int temp = 0;														//声明整型变量
		try{
			temp =i/j;														//如果产生异常,则执行catch
		}catch(Exception e) {										//捕获异常
			throw e;															//把异常交给被调用处
		}finally{																//不管是否产生异常都执行此代码
			System.out.println("******计算结束******");
		}
		return temp;														//返回计算结果
	}
}

//主类
//Function        : 	throw_demo
public class throw_demo {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		Math m =new Math();										//实例化Math对象
		try{																		
			System.out.println("除法操作="+m.div(1, 1));
		} catch (Exception e){										//进行异常的捕获
			System.out.println("异常产生:"+ e );			//打印异常
		}
		
		
	}

}
原文地址:https://www.cnblogs.com/tonglin0325/p/5243265.html